使用平分进行平方根计算

  • 本文关键字:平方根计算 python
  • 更新时间 :
  • 英文 :


我有下面的代码,应该使用平分来找到平方根,但由于某些原因,它不会。当我想找到9的平方根时,我得到4.5。

y = float(input('Enter the number that you want to find the square root of: '))
z = y
x = 0
ans = 0
while abs(ans**2 - abs(y)) > 0.0001 and ans <= x:
ans = (x + y) / 2.0
if ans**2 < z:
x = ans
else:
y = ans

print 'The square root of', z, 'is', ans

您需要检查ans <= y,因为在这种情况下,y是您的右边界。此外,您需要将ans**2z的绝对值进行比较,而不是将y与CCD_3进行比较,因为您正在循环中更改y

while abs(ans**2 - abs(z)) > 0.00001 and ans <= y:   
ans = (x + y) / 2.0
if ans**2 < z:
x = ans
else:
y = ans

数字x的平方根:sqrt=x**(1.0/2)

备选方案:

import math
math.sqrt(x)

使用平分算法:

y = float(input('Enter the number that you want to find the square root of: '))
num = y
x = 0
ans = 0
while abs(ans**2 - abs(num)) > 0.0001 and ans <= y:
ans = (x + y) / 2.0
if ans**2 < num:
x = ans
else:
y = ans
print 'The square root of', num, 'is', ans

Keiwan已经解释了脚本的错误,但这里有一种稍微不同的组织逻辑的方法。我更改了一些变量名,使代码更可读,并将其放入一个函数中,使其更易于使用。下面的代码适用于Python 2或Python 3,尽管浮点数字的打印方式略有不同。

from __future__ import print_function, division
def sqrt_bisect(z, tol=1E-12):
''' Find the square root of `z` by bisection, with tolerance `tol` '''
lo, hi = 0, z
while True:
mid = (lo + hi) / 2.0
delta = mid * mid - z
if abs(delta) < tol:
break
if delta > 0:
#Too high
hi = mid
else:
#Too low
lo = mid
return mid
for z in (1, 9, 16, 200):
x = sqrt_bisect(z)
print(z, x, x*x)

输出

1 1.0 0.999999999999
9 3.0 9.0
16 4.0 16.0
200 14.1421356237 200.0

(该输出是使用Python 2创建的)。

为了好玩,这里有一个更紧凑的函数变体。

这个版本使用了一个名为bounds的列表,而不是使用单独的lohi变量来存储我们平分的区间的边界。语句bounds[delta > 0] = mid之所以有效,是因为False在数字上等于零,而True等于一。因此当CCD_ 14为正时,CCD_。这是一个聪明的技巧,但如果你不习惯这种构造,它确实会让代码变得更难阅读。

def sqrt_bisect(z, tol=1E-12):
''' Find the square root of `z` by bisection, with tolerance `tol` '''
bounds = [0, z]
while True:
mid = sum(bounds) / 2.0
delta = mid * mid - z
if abs(delta) < tol:
break
bounds[delta > 0] = mid
return mid

最新更新