牛顿法迭代求根c语言实现

#include <math.h>

/**********************************************************************************************
Function: fzero_newton
Description: 牛顿法求单变量方程的零点
Input: 函数指针pFunc,用于定义函数的参数指针pParams,差商近似一阶导数的微步长deltaX,迭代初值x0,
	   求解精度tol,最大迭代次数maxIterations
Output: 求解结果x
Input_Output: 无
Return: 求解成功返回1,否则返回0
Author: Marc Pony(marc_pony@163.com)
***********************************************************************************************/
int fzero_newton(double(*pFunc)(double, void*), void* pParams, double deltaX, double x0, double tol, int maxIterations, double* x)
{
	int iterations;
	double f, df, f_;

	iterations = 0;
	*x = x0;
	f = tol + 1.0;
	while (fabs(f) > tol)
	{
		f = (*pFunc)(*x, pParams);
		f_ = (*pFunc)(*x + deltaX, pParams);
		df = (f_ - f) / deltaX;
		*x = *x - f / df;

		iterations++;
		if (iterations > maxIterations)
		{
			return 0;
		}
	}
	return 1;
}


typedef struct _Params
{
	double a, b, c;
}Params;


double fun(double x, Params* p)
{
	return p->a * x * x + p->b * x + p->c;
}

void main()
{
	double deltaX = 0.001;
	double x0 = 30.0;
	double tol = 1.0e-12;
	int status, maxIterations = 20;
	double x;
	Params params;

	params.a = 1.0;
	params.b = -3.0;
	params.c = 2.0;

	status = fzero_newton(fun, &params, deltaX, x0, tol, maxIterations, &x);
}

牛顿法及更高阶的迭代求根方法参考网站:Newton’s method and high order iterations

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值