from sys import argv
script, k,epsilon = argv
def find_square_root(k, epsilon):
guess = k/2
while abs(guess**2 -k) >= epsilon:
guess = guess - (guess**2 -k)/(2*guess)
print(f"Square root of {k} is about {guess}.")
k = float(argv[1])
epsilion = float(argv[2])
find_square_root(k, epsilion)
运行它并来:
$ python3 successive_approximation.py 128 0.001
Square root of 128.0 is about 33.0.
Square root of 128.0 is about 18.439393939393938.
Square root of 128.0 is about 12.690526879310774.Square root of 128.0 is about 11.388395266147043.
Square root of 128.0 is about 11.31395340237364.
Square root of 128.0 is about 11.313708501635368.
如何使用Newton的方法查找多维数据集根目录?
答案 0 :(得分:1)
关注this link:
def find_cube_root(k, epsilon):
guess = k
while(((1/3)*(2*guess + k/guess**2))**3 - k >= epsilon):
guess = (1/3)*(2*guess + k/guess**2)
print(f"Cube root of {k} is about {guess}.")
find_cube_root(100, .001)
输出:
Cube root of 100 is about 66.66999999999999.
Cube root of 100 is about 44.4541659167229.
Cube root of 100 is about 29.65297823132699.
Cube root of 100 is about 19.806561134963502.
Cube root of 100 is about 13.28934310575367.
Cube root of 100 is about 9.048305445603736.
Cube root of 100 is about 6.4393440686740675.
Cube root of 100 is about 5.096783929887992.
Cube root of 100 is about 4.6810321649028035.
Cube root of 100 is about 4.641920257658932.