38 lines
788 B
Python
38 lines
788 B
Python
import math
|
|
|
|
|
|
def f(x):
|
|
return x**2 - 30
|
|
|
|
def df(x):
|
|
return 2*x
|
|
|
|
|
|
def NewtonSolve(fx, dfx, x0, err, N0):
|
|
count = 0
|
|
x1 = x0 + 1 + err
|
|
while abs(x1 - x0) > err or abs(fx(x1)) > err: # 添加条件修正根误差太大的问题
|
|
if abs(dfx(x1)) < 1e-10:
|
|
return None, 0
|
|
x1 = x0 - fx(x0) / dfx(x0)
|
|
count += 1
|
|
if count > N0:
|
|
return None, -1
|
|
x0 = x1
|
|
return x1, 1
|
|
|
|
def FindRootZone(fx,start,stop,step):
|
|
x = start
|
|
while x < stop:
|
|
if fx(x) * fx(x+step) < 0:
|
|
return x
|
|
x += step
|
|
return None
|
|
|
|
if __name__ == "__main__":
|
|
err = 1e-4
|
|
N0 = 100
|
|
|
|
x0 = FindRootZone(f, 5, 6, 0.01)
|
|
result,status = NewtonSolve(f, df, x0, err,N0)
|
|
print(f"sqrt(30) = {result:.3f}") |