牛頓法的作用是使用迭代的方法來求解函數(shù)方程的根。簡(jiǎn)單地說庆聘,牛頓法就是不斷求取切線的過程泞边。更多見:iii.run
數(shù)學(xué)推導(dǎo)
假設(shè)c為原數(shù),t為c的根數(shù)问麸。
$$ t^2 \quad = \quad c$$
$$2t^2 \quad = \quad c + \quad t^2$$
$$2t \quad = \quad \frac{c}{t}+ \quad t$$
$$t \quad = \quad \frac{\frac{c}{t} + t}{2.0}$$
Java代碼實(shí)現(xiàn)
package test;
import java.io.IOException;
import java.util.Scanner;
public class QuickFindUF {
public static double sqrt (double c){
if(c<0)
return Double.NaN;
double err = 1e-15;
double t = c;
while(Math.abs(t-c/t)>err)
t = (c/t+t)/2.0;
return t;
}
public static void main(String args[]) throws IOException{
Scanner sc = new Scanner(System.in);
double a = sqrt(sc.nextDouble());
System.out.println(a);
}
}
Python代碼實(shí)現(xiàn)
c = input()
err = 1e-15
t = c
while abs(t - c/t)>err:
t = (c/t+t)/2.0
print(t)
Python代碼真心簡(jiǎn)潔啊