令f(x)=2sin(x+π/3)-x,牛顿法求解f(x)=0,过程为:
f'(x)=2cos(x+π/3)-1,任取初值x₀,令x₁=x₀-f(x₀)/f'(x₀)
然后迭代执行:x₀=x₁,x₁=x₀-f(x₀)/f'(x₀),直到|x₁-x₀|<=10⁻⁸,x₁即为所求
C语言代码如下:
#include<stdio.h>
#include<math.h>
#define PI 3.141592653589793
int main() {
double x0 = PI; // 初值任取
double x1 = x0-(2*sin(x0+PI/3)-x0)/(2*cos(x0+PI/3)-1);
while (fabs(x1 - x0) > 1e-8) {
x0 = x1;
x1 = x0-(2*sin(x0+PI/3)-x0)/(2*cos(x0+PI/3)-1);
}
printf("%.15f\n", x1);
return 0;
}
运行结果如图:
python代码如下:
import math
x0 = math.pi # 初值任取
x1 = x0-(2*math.sin(x0+math.pi/3)-x0)/(2*math.cos(x0+math.pi/3)-1)
while abs(x1-x0) > 1e-8:
x0 = x1
x1 = x0-(2*math.sin(x0+math.pi/3)-x0)/(2*math.cos(x0+math.pi/3)-1)
print(x1)
运行结果为:
与C语言结果一致~