//牛顿法求解(x-1)^3-x^2+x的根
#include<stdio.h>
#include<math.h>
//牛顿法
const double precision=1e-5;//定义精度
double f(double x);
double df(double x);
int main()
{
printf("The function expression is:\n");
printf("(x-1)^3-x^2+x\n");
printf("input initial value:\n");
double x0=0;
scanf("%lf",&x0);//输入初始迭代数值
int k=0;//定义迭代
printf(" k x(k) f(x) f'(x)\n");
while(fabs(f(x0))>precision)
{
double x1;
x1=x0-f(x0)/df(x0);
printf("%6d%12lf%12lf%12lf\n",k,x0,f(x0),df(x0));//输出每一次迭代的k,xk,f(xk),f'(xk)
x0=x1;
k=k+1;
}
printf("%6d%12lf%12lf%12lf\n",k,x0,f(x0),df(x0));//输出最后一次的结果(while循环中并没有输出完整的最后一次结果
printf("the final approximate root by Newton-iteration:\n");
printf("%lf",x0);
return 0;
}
double f(double x)//定义原函数
{
return (x-1)*(x-1)*(x-1)-x*x+x;
}
double df(double x)//定义导数
{
return 3*(x-1)*(x-1)-2*x+1;
}
使用C语言编写二分法和牛顿法求解给定一元函数的根
//二分法求解(x-1)^3-x^2+x在区间[2,3]的根
#include<stdio.h>
#include<math.h>
const double precision=1e-5;//定义精度
double f(double x);//定义函数
int main(){
printf("the function expression:\n");
printf("(x-1)^3-x^2+x\n");
double a=0,b=0;
printf("the interval of the root:\n");
scanf("%lf %lf",&a,&b);//输入初始区间
printf(" a b mid f(a) f(b) f(mid) k\n");
double mid;
mid=(a+b)/2;
int k=0;
if(f(a)*f(b)<0)
{
while(fabs(f(mid))>precision)//循环条件为|f(x)|>10^-5
{
mid=(a+b)/2;
printf("%12lf%12lf%12lf%12lf12%12lf%12lf%4d\n",a,b,mid,f(a),f(b),f(mid),k);
if(f(a)*f(mid)<0)//如果a与mid的函数值异号,新区间为[a,mid]
{
a=a;
b=mid;
}
if(f(b)*f(mid)<0)//如果b与mid的函数值异号,新区间为[mid,b]
{
a=mid;
b=b;
}
mid=(a+b)/2;//找到新区间[a,b],求出新的mid
k=k+1;
}
}//找到中间值的绝对值<10^-5,循环终止
printf("%12lf%12lf%12lf%12lf12%12lf%12lf%4d\n",a,b,mid,f(a),f(b),f(mid),k);
printf("the final approximate root:\n");
printf("%lf",mid);
return 0;
}
double f(double x)//定义函数
{
return (x-1)*(x-1)*(x-1)-x*x+x;
}