c语言编程牛顿迭代法,C语言编写牛顿迭代法的跟踪

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

#include 

#include

float f(float x) /*定义f函数,以实现f(x)=x*x*x+x*x-3*x-3*/

{

float y;

y=((x+1)*x-3.0)*x-3.0;

return y;

}

float g(float x) /*定义g函数,为f函数的导函数*/

{

float y;

y=(3.0*x+2.0)*x-3.0;

return y;

}

float h(float x) /*定义h函数,以实现x*x*x=-x*x+3*x+3*/

{

float y;

y=(3.0-x)*x+3.0;

return y;

}

rootA() /*定义rootA函数,以实现用二分法求近似根*/

{

int i=0;

float x,y,x1=0,x2=0,y1=0,y2=0;

do

{

printf("Input x1=");

scanf("%f",&x1);

printf("Input x2=");

scanf("%f",&x2);

y1=f(x1);

y2=f(x2);

}

while (y1*y2>=0); /*定义变量x1,x2为区间的两端点,同时保证两个端点的函数值相异*/

do

{

x=(x1+x2)/2;

y=f(x);

if(fabs(y)<1e-6)

break;

if(y*y1>0)

{

x1=x;

y1=y;

}

else

x2=x;

i=i+1; /*定义变量i以计算迭代次数*/

}

while (fabs(x2-x1)>=1e-6); /*设定精确度为1e-6*/

printf("The running number is %d\n",i);

printf("A root of equation is %7f\n",x);

}

rootB() /*定义rootB函数,以实现用基本迭代法求近似根*/

{

float x0=0,x1=0,j;

int k=0,N;

printf("Input the divisor:"); /*选定初值*/

scanf("%f",&x0);

printf("Input the number:"); /*输入最大迭代次数*/

scanf("%d",&N);

printf("Input the Precision:"); /*输入精度*/

scanf("%f",&j);

do

{

x1=pow(h(x0),(1.0/3.0)); /*建立迭代格式*/

if(fabs(x1-x0)

{

printf("A root of equation is %7f\n",x1);

break;

}

x0=x1;

k=k+1;

}while (k<=N);

if(k>N)

printf("It is Failure!\n");

if(k<=N)

printf("The running number is %d\n",k);

}

rootC() /*定义rootC函数,以实现用牛顿切线法求近似根*/

{

float x0,x1,j;

int N,k=0;

printf("Input the divisor:");

scanf("%f",&x0);

printf("Input the number:");

scanf("%d",&N);

printf("Input the Precision:");

scanf("%f",&j);

for(k=0;k<=N;k=k+1)

{

if(fabs(g(x0))<=1e-6)

{

printf("It is Singular!\n");

break;

}

else

{

x1=x0-(f(x0)/g(x0)); /*迭代函数*/

if(fabs(x1-x0)

{

printf("A root of equation is %7f\n",x1);

break;

}

x0=x1;

}

}

if(k>N)

printf("It is Failure!\n");

else

printf("The running number is %d\n",k);

}

void main() /*主函数*/

{

int choose;

char yes_no;

printf("Which method do you want to choose?(1,2,3)\n");

printf("1---------ErFenFa\n");

printf("2---------JiBenDieDaiFa\n");

printf("3---------NiuDunQieXianFa\n");

do

{

printf("You choose is ");

scanf("%d",&choose);

switch(choose)

{

case 1: rootA();break;

case 2: rootB();break;

case 3: rootC();break;

case 0: break;

default: printf("It is error!\n");

}

if(choose==0)

break;

printf("Are you want to contain?(Y/N)");

do

{

scanf("%c",&yes_no);

}

while (yes_no!='Y'&&yes_no!='y'&&yes_no!='N'&&yes_no!='n');

}

while (yes_no=='Y'||yes_no=='y');

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值