我正在尝试编写一个程序,使用Sidi方法找到三次多项式函数的根,该方法类似于牛顿方法和正割方法。唯一的区别是使用插值多项式而不是函数的导数。我还必须用50个猜测来测试我的代码,并且我已经尝试编写代码但是当我执行它时没有任何反应。这是我的代码
double f(double x)
{
return ((3*x*x*x)-(6*x*x)-(6*x)-5);//polynomial equation
}
double y(double z)
{
return ((17.8*z*z*z)-(34.5*z*z)+(199.7*z)+30);//interpolation equation
}
double dy (float z)
{
return ((53.4*z*z)-(69*z)+199.7);//derivative of interpolation equation
}
main()
{
double i;
int maxitr = 10;
int itr;
double a;
double b;
double maxdec = 0.000001;
for(i=1; i<= 50; i++){
printf("Input guess ");
scanf("%lf", i);
for(itr = 1; itr < maxitr; itr++){
a = f(i) / dy(i);
b = i - a;
if(fabs(a) < maxdec){
printf("root: %lf", b);
return 0;
}
i = b;
}
}
答案 0 :(得分:0)
希望这会对你有所帮助。我的程序解决了这个等式f(x)= x ^ 7-1000 = 0.您可以通过编辑void f(double x[],int x1,int x2)
函数来添加等式。你还可以添加任何你想要的东西。
#include<stdio.h>
#include<math.h>
void f(double x[],int x1,int x2);
int main()
{
double x[50];
int x1,x2;
printf("Enter x1:\n");
scanf("%d",&x1);
printf("Enter x2:\n");
scanf("%d",&x2);
printf("\nCalculating....\n");
f(x,x1,x2);
return 0;
}
void f(double x[],int x1,int x2)
{
// Assuming Equation is x^7 - 1000
// you can edit this code to keep your
// own equation
int i,prec=10000;
double a,b,num;
double denom,d1,d2;
x[0] = 0.00; //let's start with index 1 instead of 0
x[1] = x1;
x[2] = x2;
printf("x[2]:%f\n",x[2]);
for(i=3;i<=50;i++)
{
num = pow(x[i-1],7)-1000;
d1 = (pow(x[i-1],7)-1000) - (pow(x[i-2],7)-1000);
d2 = (x[i-1] - x[i-2]);
denom = d1/d2;
x[i] = x[i-1] - num/denom;
printf("x[%d]:%f\n",i,x[i]);
a= (long int)(x[i]*prec);
b= (long int)(x[i-1]*prec);
if(a == b)
{
break;
}
}
printf("x[%d]=%f and x[%d]=%f are apprx equal!\n",i-1,x[i-1],i,x[i]);
}
其中,
num
是(x2)^7 - 1000
d1
是((x2)^7 - 1000)-((x1)^7-1000)
d2
是x2-x1
denom
是d1/d2