This commit is contained in:
2025-05-13 15:01:31 +08:00
parent af50496fdc
commit ecdae2085b
3 changed files with 134 additions and 0 deletions

60
159-5.py Normal file
View File

@@ -0,0 +1,60 @@
import math
def f1(x):
return x**2 + 10*math.cos(x)
def df1(x):
return 2*x - 10*math.sin(x)
def f2(x):
return 1 + math.atan(x) - x
def df2(x):
return 1/(1+x**2) - 1
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-5
N0 = 100
x0 = 1.6
result,status = NewtonSolve(f1, df1, x0, err,N0)
if status == 1:
print(f"f1收敛 解为: {result}")
elif status == -1:
print("f1不收敛")
else:
print("f1导数为0无法收敛")
x0 = FindRootZone(f2, -5, 5, 0.01)
result, status = NewtonSolve(f2, df2, x0, err,N0)
if status == 1:
print(f"f2收敛 解为: {result}")
elif status == -1:
print("f2不收敛")
else:
print("f2导数为0无法收敛")

38
159-6.py Normal file
View File

@@ -0,0 +1,38 @@
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}")

36
159-7.py Normal file
View File

@@ -0,0 +1,36 @@
def FindRootZone(fx,start,stop,step):
x = start
while x < stop:
if fx(x) * fx(x+step) < 0:
return x
x += step
return None
# 求n次方根迭代过程如下
def GetNthRoot(a,n):
if a < 0 and n % 2 == 0:
print("Cannot compute even root of negative number")
return None
fx = lambda x: x**n - a
dfx = lambda x: n * x**(n-1)
err = 1e-10
N0 = 100
x0 = 0
if a > 0:
x0 = FindRootZone(fx, 0, a, 0.01)
else:
x0 = FindRootZone(fx, a, 0, 0.01)
count = 0
x1 = x0 + 1 + err
while abs(x1 - x0) > err or abs(fx(x1)) > err: # 添加条件修正根误差太大的问题
x1 = x0 - fx(x0) / dfx(x0)
count += 1
if count > N0:
return None
x0 = x1
return x1
if __name__ == "__main__":
re = GetNthRoot(30, 5)
print(re)