割线法

来源:互联网 发布:二次开发 软件著作权 编辑:程序博客网 时间:2024/04/26 23:57

 上一篇文章中的牛顿迭代法的收敛速度快,但每迭代一次,除需计算f(x)的值外还要计算f'(x)的值。如果f(x)比较复杂,计算f'(x)的工作量可能很大。为避免使用导数值,我们可以采用割线法求方程的根。

 

实例代码:

  1. /*割线法*/
  2. #include <stdio.h>
  3. #include <math.h>
  4. float (*f)(float) = NULL;
  5. float f1(float x)
  6. {
  7.     return x*x - exp(x);
  8. }
  9. float f2(float x)
  10. {
  11.     return x*exp(x) - 1;
  12. }
  13. float f3(float x)
  14. {
  15.     return log10(x) + x -2; 
  16. }
  17. float Secant(float x0,float x1)
  18. {
  19.     return (x1 - (f(x1)*(x1-x0))/(f(x1)-f(x0)));
  20. }
  21. void main()
  22. {
  23.     int number,k=2;
  24.     float x0,x1,x2;
  25.     printf("请输入要求解的方程序号(1/2/3) : ");
  26.     scanf("%d",&number);
  27.     switch(number)
  28.     {
  29.     case 1: f = f1;break;
  30.     case 2: f = f2;break;
  31.     case 3: f = f3;break;
  32.     default: printf("没有这样的方程!/n");break;
  33.     }
  34.     if (f)
  35.     {
  36.         printf("请输入x0 x1的值:");
  37.         scanf("%f%f",&x0,&x1);
  38.         printf("x[0] = %-10f,x[1] = %-10f ",x0,x1);
  39.         while (1)
  40.         {
  41.             if (k>=21) break;
  42.             x2 = Secant(x0,x1); 
  43.             x0 = x1;
  44.             x1 = x2;
  45.             printf("x[%d] = %-10f  ",k,x2);
  46.             k++;
  47.             if (k%3==0) printf("/n");
  48.         }
  49.     }
  50. }

 

原创粉丝点击