首页 > 解决方案 > 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()

标签: pythondigitspi

解决方案


float数据类型对您可以获得的精确度有限制。50 位数就在这个范围之内。

我建议使用 aDecimal来表示具有如此高精度的数字:

>>> from decimal import Decimal
>>> d = Decimal('3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270938521105559644622948954930381964428')
>>> format(d, ".50f")
'3.14159265358979323846264338327950288419716939937511'
>>> format(d, ".204f")
'3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067982148086513282306647093844609550582231725359408128481117450284102709385211055596446229489549303819644280'

通过这种方式,您可以在不丢失精度的情况下对其进行数学运算,而“将其视为字符串”不会让您这样做。


推荐阅读