fork download
  1. // ------------------------------------------------------
  2. // newton-method
  3. //
  4. #include <stdio.h>
  5. #include <math.h>
  6. #include <stdlib.h>
  7. // ------------------------------------------------------
  8. double A, B, C, M, N;
  9. double func(double x)
  10. {
  11. // func(x) = A*e^(m*t)+B*e^(n*t) - C
  12. return
  13. A * exp(M*x) + B * exp(N*x) - C;
  14. }
  15.  
  16. double funcd(double x)
  17. {
  18. // funcd(x) = func'(x)
  19. // funcd(x) = A*m*e^(m*t)+B*n*e^(n*t)
  20. return
  21. A * M * exp(M*x) + B * N * exp(N*x) - C;
  22. }
  23.  
  24. // -------------------------------------------------------
  25. double NewtonRoot(double x0,/* 初點 */
  26. double (*fx)(double), /* 適應函式*/
  27. double (*fd)(double), /* 微分函式*/
  28. double eps, /* 容許誤差*/
  29. int max_itera) /* 最大迭代*/
  30. {
  31. double x=x0;
  32. do{
  33. x0=x;
  34. x = x0 - fx(x0) / fd(x0);
  35. }while(fabs(x-x0)>eps && max_itera--);
  36. return x;
  37. }
  38.  
  39. // -------------------------------------------------------
  40. int main()
  41. {
  42. const double eps=1E-15;
  43. const int max_iterator=1000000;
  44. double x0, x;
  45.  
  46. puts("A * e^(mx) + B * e^(nx) - C = 0 < newton method >");
  47. printf("input A : "); scanf("%lf", &A);
  48. printf("input B : "); scanf("%lf", &B);
  49. printf("input C : "); scanf("%lf", &C);
  50. printf("input N : "); scanf("%lf", &N);
  51. printf("input M : "); scanf("%lf", &M);
  52. printf("input x0: "); scanf("%lf", &x0);
  53.  
  54. x = NewtonRoot(x0, func, funcd, eps, max_iterator);
  55.  
  56. puts("");
  57. printf("x : %.15lf\n", x);
  58. printf("func(x) : %.15lf\n", func(x));
  59. // system("pause"); // 看不到結果加入這行
  60. return 0;
  61. }
Success #stdin #stdout 0.01s 1724KB
stdin
1.234
3.145
100.145
3.337
6.145
5

1000.247
123.597
12347.345
-10.2
-5.7
-7.8

1
2
4
8
16
0
stdout
A * e^(mx) + B * e^(nx) - C = 0 < newton method >
input A : input B : input C : input N : input M : input x0: 
x       : 0.660860018556372
func(x) : 0.000000000000081