Python 用二分法计算平方根
我有下面的代码,它应该使用二分法求平方根,但由于某些原因它不会。当我想找到9的平方根时,我得到4.5Python 用二分法计算平方根,python,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 <
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
y=float(输入('输入要查找其平方根的数字:'))
z=y
x=0
ans=0
而abs(ans**2-abs(y))>0.0001和ansx的平方根: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
y=float(输入('输入要查找其平方根的数字:'))
num=y
x=0
ans=0
虽然abs(ans**2-abs(num))>0.0001和ans您需要检查ans 0.00001和ansKeiwan是否解释了脚本的错误,但这里有一种稍微不同的方法来组织逻辑。我更改了一些变量名,使代码更可读,并将其放入函数中,使其更易于使用。下面的代码适用于Python2或Python3,尽管在浮点数的打印方式上有一些细微的差异
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)
(该输出是使用Python 2创建的)
为了好玩,这里有一个更紧凑的函数变体
此版本使用名为bounds
的列表,而不是使用单独的lo
和hi
变量来存储我们正在平分的区间边界。语句bounds[delta>0]=mid
之所以有效,是因为False
在数字上等于零,True
等于一。所以当delta
为正时,bounds[delta>0]
相当于bounds[1]
。这是一个聪明的技巧,但如果您不习惯这种结构,它确实会使代码更难阅读
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
def sqrt_对分(z,tol=1E-12):
''通过二分法求'z'的平方根,公差为'tol''
边界=[0,z]
尽管如此:
中间=总和(界限)/2.0
delta=mid*mid-z
如果abs(delta)0]=中间
中途返回
如果以下答案之一解决了您的问题,您应该接受它(单击相应答案旁边的复选标记)。这有两件事。它让每个人都知道你的问题已经解决到令你满意的程度,并让帮助你的人相信你的帮助。请参阅以获取完整的解释。
1 1.0 0.999999999999
9 3.0 9.0
16 4.0 16.0
200 14.1421356237 200.0
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