弦截法C语言实现如下:
//求根函数
float f( float x ){
float y;
y = ((a * x + b) * x + c) * x + d;
return (y);
}
//求解与x轴交点
float xpoint( float x1, float x2 ){
float y;
y = ( x1 * f(x2) - x2 * f(x1) ) / ( f(x2) - f(x1) );
return (y);
}
/*
[ x1, x2 ]为给定的求根区间
*/
float root( float x1, float x2 ) {//需满足f(x1)与f(x2)异号
int i;
float x, y, y1;
float a,b,c,d;
printf("input a,b,c,d:\r\n");
scanf("%f,%f,%f,%f",&a,&b,&c,&d);
y1 = f(x1);
do{
x = xpoint(x1, x2);//求解与x轴交点
y = f( x );
if( y * y1 > 0 ){
x1 = x;
y1 = y;
} else {
x2 = x;
}
} while( fabs(y) >= 1e-6);//计算精度
printf( "the value is %.14f\r\n", x );
return (x);
}
牛顿迭代法C语言实现如下:
/*
a 三次系数
b 二次系数
c 一次系数
d 常系数
num 计算初值
*/
float solute( float a, float b, float c, float d, float num){
float x ,x0 ,f ,f1;
x = num;
do{
x0 = x;
f = (( a*x0 + b )*x0 + c )*x0 + d;
f1 = ( 3*a*x0 + 2*b )*x0 + c;
x = x0 - f / f1;
cnt++;
} while ( fabs( x - x0 ) > 1e-6 );
printf( "the value is %.14f \r\n", x );
return( x );
}
二分法C语言实现如下:
/*
a 三次系数
b 二次系数
c 一次系数
d 常系数
*/
void dichotomy( float a, float b, float c, float d ){
float a,b,c,d;
float x1,x2,x0,fx1,fx2,fx0;
//需满足f(x1)与f(x2)异号,且x1 < x2
do{
//输入求根范围
printf("input x1,x2:\r\n");
scanf("%f,%f",&x1, &x2);
fx1 = ((a * x1 + b) * x1 + c) * x1 + d;
fx2 = ((a * x2 + b) * x2 + c) * x2 + d;
} while( fx1 * fx2 >= 0 );
do{
x0 = ( x1 + x2 ) / 2;
fx0 = (( a * x0 + b) * x0 + c) * x0 + d;
if( (fx0 * fx1) < 0 ){
x2 = x0;
fx2 = fx0;
} else {
x1 = x0;
fx1 = fx0;
}
} while( fabs( fx0 ) >= 1e-6 );//求根精度
printf( "the value is %.14f \r\n", x0 );
}