如何在Python计算的高精度π值整数中指定位置添加小数点
解决方案
要在整数形式的π字符串(如3141592653589792144990845475911)的数字3后插入小数点,直接操作字符串是最可靠的方式——因为你的数值是通过整数运算保证精度的,转成浮点数会丢失精度,而字符串切片/拼接可以完美保留所有数字。
具体修改步骤
在你的代码最后一行print之前,添加字符串处理逻辑:
# 处理字符串,在第一个字符后插入小数点 if enc: formatted_pi = enc[0] + "." + enc[1:] else: formatted_pi = enc # 处理空字符串的边界情况
然后修改打印语句:
print(f"The value of pi at {p} of precision is : {formatted_pi}")
为什么format方法没生效?
如果你之前尝试用format处理整数ApproximationPi,会因为Python的浮点数精度限制(通常只有15-17位有效数字),导致超长整数转浮点数时丢失末尾的精度,而且无法保留你计算出的所有位数。直接操作字符串则完全不会有这个问题,能完整保留你通过整数运算得到的所有精度。
完整修改后的代码片段
num = 1 den1 = 2 den2 = 3 k=1 p = 15 # precision ApproximationPi=0 index=-p enc='' while ApproximationPi > 0 or index <= 0: print("ApproximationPi =", ApproximationPi,"k =", k, "index =", index) if index == 0: enc =str(+ApproximationPi) break enc = str(ApproximationPi % 10)+enc x=(10**p*num)//den1**k #first fraction in the parenthese y=(10**p*num)//den2**k #second fraction in the parenthese z=(10**p*4//k) #fraction that is multiplied to the parenthese ApproximationPi += z*(x+y) #result k += 2 a=(10**p*num)//den1**k #first fraction in the parenthese b=(10**p*num)//den2**k #second fraction in the parenthese c=(10**p*4//k) #fraction that is multiplied to the parenthese ApproximationPi += -c*(a+b) k += 2 index += 1 # 新增处理逻辑 if enc: formatted_pi = enc[0] + "." + enc[1:] else: formatted_pi = enc print(f"The value of pi at {p} of precision is : {formatted_pi}")
这样运行后,输出就会变成3.141592653589792144990845475911的格式,完美符合需求。
内容的提问来源于stack exchange,提问作者Balzaque
相关产品推荐
相关产品推荐

