Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用牛顿';求一个数的平方根的方法是什么?_Python_Algorithm_Square Root_Newtons Method - Fatal编程技术网

Python 使用牛顿';求一个数的平方根的方法是什么?

Python 使用牛顿';求一个数的平方根的方法是什么?,python,algorithm,square-root,newtons-method,Python,Algorithm,Square Root,Newtons Method,这是到目前为止我的代码。我不知道为什么它不打印任何东西。我希望不是因为一些愚蠢的错误 y = float(raw_input("Enter a number you want square rooted: ")) x = 0 # Newton's Method: y = (x+y)/x + 2 while y > x: x += 0.1 if x == y/(2*y-1): print x else: pass 有什么建

这是到目前为止我的代码。我不知道为什么它不打印任何东西。我希望不是因为一些愚蠢的错误

y = float(raw_input("Enter a number you want square rooted: ")) 
x = 0 
# Newton's Method: y = (x+y)/x + 2 
while y > x:
    x += 0.1 
    if x == y/(2*y-1):
        print x 
    else:
        pass 
有什么建议或选择吗?
任何帮助都将不胜感激

你的代码根本不像牛顿的方法。以下是具有重写逻辑的代码:

y = float(raw_input("Enter a number you want square rooted: ")) 

# Solve f(x) = x^2 - y = 0 for x.
# Newton's method: Iterate new_x = x - f(x)/f'(x).
# Note that f'(x) = 2x. Thus new_x = x - (x^2 - y)/(2x).
prevx = -1.0
x = 1.0
while abs(x - prevx) > 1e-10:  # Loop until x stabilizes
    prevx = x
    x = x - (x*x - y) / (2*x)
print(x)

旁注:迭代逼近平方根的另一种类似方法是。

加一,尽管我将停止条件更改为:
,而y-x*x>1e-10:
;)@阿尔法辛:你怎么知道在它收敛到平方根之前,
x
的估计值总是小于
y
?是的,你可以这样做:
abs(y-x*x).