python - PI 小数点后第 n 位
问题描述
我想制作一个程序,它将在 PI 号中返回小数点后的第 n 个数字。只要我不将 n 设置为高于 50,它就可以很好地工作。我可以修复它还是 Python 不允许这样做?
这是我的代码:
pi = 3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270938521105559644622948954930381964428
def nth_pi_digit(n=input("How many digits after decimal you would like to see?(PI number): ")):
try:
n = int(n)
if n <= 204:
return print(format(pi, f".{n}f"))
else:
print("Sorry, we have pi with 204 digits after decimal, so we'll print that")
return print(format(pi, ".204f"))
except:
print("You need to put a integer digit")
nth_pi_digit()
解决方案
float
数据类型对您可以获得的精确度有限制。50 位数就在这个范围之内。
我建议使用 aDecimal
来表示具有如此高精度的数字:
>>> from decimal import Decimal
>>> d = Decimal('3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270938521105559644622948954930381964428')
>>> format(d, ".50f")
'3.14159265358979323846264338327950288419716939937511'
>>> format(d, ".204f")
'3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102709385211055596446229489549303819644280'
通过这种方式,您可以在不丢失精度的情况下对其进行数学运算,而“将其视为字符串”不会让您这样做。
推荐阅读
- javascript - `document.appendChild()` 会重新加载所有的 html 页面吗?
- sql - SQL Join 仅存在于右表中的值
- azure - 如何在 C# 测试中从 azure devops(前 vsts)的测试用例中获取参数值?
- javascript - 在 wp_footer() 之后调用 JS 脚本;
- javascript - 带有laravel mix和eslint的vuejs路由器中的意外令牌导入
- android - Android 在后台杀死我的应用程序
- c# - SwipeItem XAML 绑定被忽略
- python - 在 python/scapy 中采样流量
- javascript - 如何让按钮在某个时间点后更改其步骤而不会失去价值?
- python - DataFrame 中系列的平均值