我试图在 python 中近似 2 的平方根

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


这是我写的代码。我的想法是在x的末尾放一个数字(在0~9之间(,然后把它平方然后看看它是否小于2,选择最大的

x = 1.4

for n in range(21):
next_num = [0,1,2,3,4,5,6,7,8,9]
candidate = []
for number in next_num:
if float(str(x)+str(number))*float(str(x)+str(number))<2:
candidate.append(number)

x = float(str(x)+str(max(candidate)))

print(x)

但问题是我只得到1.414213562373这13位数我试着在范围内输入更大的数字,但我只得到了这个

谢谢

float没有足够的精度。您需要decimal模块:

from decimal import Decimal, getcontext
getcontext().prec = 51 # the "1" before the decimal point counts, too
x = Decimal("1.4")
for n in range(50):
next_num = [0,1,2,3,4,5,6,7,8,9]
candidate = 0
for number in next_num:
if Decimal(str(x)+str(number))*Decimal(str(x)+str(number))<2:
candidate = number
x = Decimal(str(x)+str(candidate))
print(x)

输出:

1.414213562373095048801688724209698078569671875376946

您可以用整数近似任何根,这样您就不会受到小数位数的限制,但唯一不利的是您的输出没有小数点。

"x〃;是您要取其根的数字。"b";是第n个根。"dec";是小数位数。

def root(x,b,dec):
s = 0
n = 0
for q in range(dec):
for k in range(10):
s = n
n = 10*n+(9-k)
if(n**b > x*10**(q*b)):
n = s
else:
break
return n
Input:
root(2,2,500)
Output:
14142135623730950488016887242096980785696718753769480731766797379907324784621070388503875343276415727350138462309122970249248360558507372126441214970999358314132226659275055927557999505011527820605714701095599716059702745345968620147285174186408891986095523292304843087143214508397626036279952514079896872533965463318088296406206152583523950547457502877599617298355752203375318570113543746034084988471603868999706990048150305440277903164542478230684929369186215805784631115966687130130156185689872372

最新更新