牛顿法,也称为牛顿-拉弗森方法,是一种迭代逼近的数值计算方法,可用于求解方程的根。牛顿法也可以用来求平方根。
大神 牛顿
设要求解的数的平方根为x,则可以将问题转化为求方程f(x) = x^2 - n = 0的根,其中n为待求平方根的数。
牛顿法的迭代公式为:
x_(k+1) = x_k - f(x_k) / f'(x_k)
其中,x_k表示第k次迭代的近似解,f'(x_k)表示f(x)在x_k处的导数。
对于求平方根的问题,可以令f(x) = x^2 - n,则f'(x) = 2x。
将上述表达式代入迭代公式中,求解平方根的过程如下:
1、选择初始的近似解x_0。
2、使用迭代公式计算下一个近似解:
x_1 = x_0 - (x_0^2 - n) / (2 * x_0)
3、重复步骤2直到收敛,即达到预定的精度要求。
数学原理图示如下:
数形结合 设计斜率&导数等知识点
以下是C语言实现代码:
#include <stdio.h>
#include <math.h>
// 牛顿法求平方根可拓展
double mySqrt(int x) {
double t=1.0; //初始迭代值
double cheak; //误差
double p = 1e-2; //误差上限
do
{
t = (x / t + t) / 2.0;
cheak = t * t - x;
} while((cheak >= 0 ? cheak : -cheak) > p);
return t;
}
double myCube(int x) {
double t=1.0;
double cheak;
double p = 1e-5;
do
{
t = (x / pow(t,2) + 2*t) / 3.0;
cheak = pow(t,3) - x;
} while((cheak >= 0 ? cheak : -cheak) > p);
return t;
}
// 牛顿法求n次方根可拓展
double nthRoot(int num,int n) {
double t=1.0;
double cheak;
double p = 1e-5;
do
{
t = (num / pow(t,(n-1)) + (n-1)*t) / n;
cheak = pow(t,n) - num;
} while((cheak >= 0 ? cheak : -cheak) > p);
return t;
}
int main () {
printf("mySqrt:2的平方根 = %f",mySqrt(2));
putchar(10);
printf("myCube:2的立方根 = %f",myCube(2));
putchar(10);
printf("nthRoot:2的平方根 = %f",nthRoot(2,2));
putchar(10);
printf("nthRoot:2的立方根 = %f",nthRoot(2,3));
return 0;
}
code
实现效果如下:
res-01
res-02