牛顿迭代法.cpp
Upload User: hks123456
Upload Date: 2014-01-27
Package Size: 18k
Code Size: 1k
Category:

Algorithm

Development Platform:

Visual C++

  1. #include<iostream.h>
  2. #include<math.h>
  3. #define N 100
  4. #define EPS 1e-6
  5. #define ETA 1e-8
  6. void main()
  7. {
  8. float f(float);
  9. float f1(float);
  10. float x0,y0;
  11. float Newton(float (*)(float),float (*)(float),float);
  12. cout<<"Please input x0n";
  13. cin>>x0;
  14. cout<<"x(0)="<<x0<<endl;
  15. y0=Newton(f,f1,x0);
  16. cout<<"nThe root of the equation is x="<<(float)y0<<endl;
  17. }
  18. float Newton(float (*f)(float),float (*f1)(float),float x0)
  19. {
  20. float x1,d;
  21. int k=0;
  22. do{
  23. x1=x0-f(x0)/f1(x0);
  24. if((k++>N)||(fabs(f1(x1))<EPS))
  25. {
  26. cout<<"nNewton method faild!";
  27. return 0;
  28. }
  29. d=(fabs(x1)<1?x1-x0:(x1-x0)/x1);
  30. x0=x1;
  31. cout<<"x("<<k<<")="<<x0<<endl;
  32. }
  33. while(fabs(d)>EPS&&fabs(f(x1))>ETA);
  34. return 1;
  35. }
  36. float f(float x)
  37. {
  38. // return log(x)+x-2;
  39. return x*x*x+x*x-3*x-3;
  40. }
  41. float f1(float x)
  42. {
  43. // return 1/x+1;
  44. return 3.0*x*x+2*x-3;
  45. }