牛顿迭代模板 - 求函数零点

#include<iostream>
#include<cmath>

using namespace std;

double func(double x){
	return x * x * x * x - 3 * x * x * x + 1.5 * x * x - 4.0;
}

double dfunc(double x){
	return 4 * x * x * x - 9 * x * x + 3 * x ;
}
int Newtonmethod( double &x , int maxcyc , double precision ){
	double  x0 ,x1 ;
	int i ;
	x0 = x ;
	i = 0 ;
	while( i < maxcyc ){
		i++ ; 
		if( dfunc(x0) == 0 ) {
			cout << "迭代过程中导数为0 " << endl;
			return 0 ;
		}
		x1 = x0 - func(x0) / dfunc(x0) ; 
		
		if(abs( x1 - x0 ) < precision && abs(func( x1 )) < precision ){
			x = x1 ; 
			return 1;
		}
		else
		{
			x0 = x1 ;
		}
	}
	printf("迭代次数超过预期值!仍没有达到精度!\n");
	return 0 ; 
}
int main(void){
	 double x = 2.0 ;
	 double precision = 1e-12;
	 double result = Newtonmethod( x , 1000 , precision );
	 if( result )
	 cout << "方程根为" << x << endl;
	 else
	 cout << "迭代失败" << endl;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值