1. 简介
牛顿迭代法是求方程近似根的一种方法。
以求平方根为例。
如
x
2
=
m
x^2=m
x2=m
令
f
(
x
)
=
x
2
−
m
f(x)=x^2-m
f(x)=x2−m
则
f
′
(
x
)
=
2
x
f'(x)=2x
f′(x)=2x
函数
f
(
x
)
f(x)
f(x)在
x
0
x_0
x0处的切线方程为
g
(
x
)
=
f
′
(
x
0
)
(
x
−
x
0
)
+
f
(
x
0
)
g(x) = f'(x_0)(x - x_0) + f(x_0)
g(x)=f′(x0)(x−x0)+f(x0)
令该切线与x轴交点为
(
x
1
,
0
)
(x_1,0)
(x1,0)
x
1
=
x
0
−
f
(
x
0
)
f
′
(
x
0
)
x_1=x_0 - \frac {f(x_0)} {f'(x_0)}
x1=x0−f′(x0)f(x0)
x 1 = x 0 − x 0 2 − m 2 x 0 x_1= x_0- \frac {x_0^2-m}{2x_0} x1=x0−2x0x02−m
重复上述迭代过程,直到 x n + 1 − x n x_{n+1}-x_n xn+1−xn小于某一精度
2. 实现
迭代即可
- cpp
#include <iostream>
#include <cstring>
#include <cmath>
double my_sqrt(double x)
{
double x0 = 1;
double x1 = x0 - (x0 * x0 - x)/(2*x0);
while ( std::abs(x0-x1) > 1e-6) {
x0 = x1;
x1 -= (x1*x1 - x) / (2*x1);
}
return x0;
}
int main(int argc, char *argv[])
{
std::cout << my_sqrt(2) << std::endl;
std::cout << my_sqrt(3) << std::endl;
std::cout << my_sqrt(5) << std::endl;
return 0;
}
- go
package main
import (
"fmt"
"math"
)
func New_ton(x ,z float64) float64{
return z - (z*z - x) / (2 * z)
}
func Sqrt(x float64) float64 {
z := 1.0
for z0:= New_ton(x, z); math.Abs(z-z0) > 1e-6; z0 = New_ton(x,z0) {
z = z0
}
return z
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(3))
fmt.Println(Sqrt(5))
}