将pi打印到多个小数位 - Python

Fra*_*er 6 python pi

w3resources面临的挑战之一是将pi打印到'n'个小数位.这是我的代码:

from math import pi

fraser = str(pi)

length_of_pi = []

number_of_places = raw_input("Enter the number of decimal places you want to 
see: ")

for number_of_places in fraser:
    length_of_pi.append(str(number_of_places))

print "".join(length_of_pi)
Run Code Online (Sandbox Code Playgroud)

无论出于何种原因,它会自动打印pi而不考虑任何输入.任何帮助都会很棒:)

Mos*_*oye 10

为什么不format使用number_of_places:

''.format(pi)
>>> format(pi, '.4f')
'3.1416'
>>> format(pi, '.14f')
'3.14159265358979'
Run Code Online (Sandbox Code Playgroud)

更一般地说:

>>> number_of_places = 6
>>> '{:.{}f}'.format(pi, number_of_places)
'3.141593'
Run Code Online (Sandbox Code Playgroud)

在你原来的方法中,我猜你试图选择一些数字number_of_places作为循环的控制变量,这是非常hacky但在你的情况下不起作用,因为number_of_digits用户输入的初始化从未使用过.而是由pi字符串中的iteratee值替换.


Jon*_*ler 8

建议的解决方案使用np.pi,math.pi等只能使精度加倍(~14位),以获得更高的精度,您需要使用多精度,例如mpmath包

>>> from mpmath import mp
>>> mp.dps = 20    # set number of digits
>>> print(mp.pi)
3.1415926535897932385
Run Code Online (Sandbox Code Playgroud)

使用np.pi会产生错误的结果

>>> format(np.pi, '.20f')
3.14159265358979311600
Run Code Online (Sandbox Code Playgroud)

与真实值相比:

3.14159265358979323846264338327...
Run Code Online (Sandbox Code Playgroud)