#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, ¶ms, deltaX, x0, tol, maxIterations, &x);
}
牛顿法及更高阶的迭代求根方法参考网站:Newton’s method and high order iterations