Files
CalWay_Python/159-7.py

37 lines
933 B
Python

# 查找根区间
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) #30的5次方根###########################
print(re)