将 pi 打印到小数位

Print pi to a number of decimal places

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)

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

为什么不 format 使用 number_of_places:

''.format(pi)
>>> format(pi, '.4f')
'3.1416'
>>> format(pi, '.14f')
'3.14159265358979'

更一般地说:

>>> number_of_places = 6
>>> '{:.{}f}'.format(pi, number_of_places)
'3.141593'

在你原来的方法中,我猜你试图使用 number_of_places 作为循环的控制变量来选择一些数字,这很老套,但在你的情况下不起作用,因为初始number_of_digits 用户输入的从未被使用。它被替换为 pi 字符串中的迭代值。

使用np.pimath.pi等的建议解决方案仅适用于双精度(~14位数字),要获得更高的精度,您需要使用多精度,例如mpmath包裹

>>> from mpmath import mp
>>> mp.dps = 20    # set number of digits
>>> print(mp.pi)
3.1415926535897932385

使用 np.pi 给出了错误的结果

>>> format(np.pi, '.20f')
3.14159265358979311600

与真值对比:

3.14159265358979323846264338327...

您的解决方案似乎在错误地循环:

for number_of_places in fraser:

对于 9 个地方,结果是这样的:

for "9" in "3.141592653589793":

循环 3 次,每次在字符串中找到一个“9”。我们可以修复您的代码:

from math import pi

fraser = str(pi)

length_of_pi = []

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

for places in range(number_of_places + 1):  # +1 for decimal point
    length_of_pi.append(str(fraser[places]))

print "".join(length_of_pi)

但这仍然限制n小于len(str(math.pi)),小于Python中的15 2.给定一个严重的n,它打破了:

> python test.py
Enter the number of decimal places you want to see: 100
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    length_of_pi.append(str(fraser[places]))
IndexError: string index out of range
> 

为了做得更好,我们必须自己计算 PI -- 使用系列评估是一种方法:

# Rewrite of Henrik Johansson's (Henrik.Johansson@Nexus.Comm.SE)
# pi.c example from his bignum package for Python 3
#
# Terms based on Gauss' refinement of Machin's formula:
#
# arctan(x) = x - (x^3)/3 + (x^5)/5 - (x^7)/7 + ...

from decimal import Decimal, getcontext

TERMS = [(12, 18), (8, 57), (-5, 239)]  # ala Gauss

def arctan(talj, kvot):

    """Compute arctangent using a series approximation"""

    summation = 0

    talj *= product

    qfactor = 1

    while talj:
        talj //= kvot
        summation += (talj // qfactor)
        qfactor += 2

    return summation

number_of_places = int(input("Enter the number of decimal places you want: "))
getcontext().prec = number_of_places
product = 10 ** number_of_places

result = 0

for multiplier, denominator in TERMS:
    denominator = Decimal(denominator)
    result += arctan(- denominator * multiplier, - (denominator ** 2))

result *= 4  # pi == atan(1) * 4
string = str(result)

# 3.14159265358979E+15 => 3.14159265358979
print(string[0:string.index("E")])

现在我们可以取一个很大的值n:

> python3 test2.py
Enter the number of decimal places you want: 100
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117067
> 

由于这个问题已经有了有用的答案,我想分享一下我是如何为同样的目的创建一个程序的,这个程序与问题中的非常相似。

from math import pi
i = int(input("Enter the number of decimal places: "))
h = 0
b = list()
for x in str(pi):
    h += 1
    b.append(x)
    if h == i+2:
        break

h = ''.join(b)
print(h)

感谢阅读。

例如mpmath

from mpmath import mp
def a(n):
   mp.dps=n+1
   return(mp.pi)

为什么不直接使用:

import numpy as np

def pidecimal(round):
    print(np.round(np.pi, round)) 

这就是我所做的,非常初级但有效(最多 15 位小数):

pi = 22/7
while True:

    n = int(input('Please enter how many decimals you want to print: '))

    if n<=15:
        print('The output with {} decimal places is: '.format(n))
        x = str(pi)
        print(x[0:n+2])
        break
    else:
        print('Please enter a number between 0 and 15')

很好的答案!有很多方法可以实现这一目标。看看我在下面使用的这个方法,它可以处理任意小数位直到无穷大:

#import multp-precision module
from mpmath import mp
#define PI function
def pi_func():
    while True:
        #request input from user
        try:
             entry = input("Please enter an number of decimal places to which the value of PI should be calculated\nEnter 'quit' to cancel: ")
             #condition for quit
             if entry == 'quit':
                 break
             #modify input for computation
             mp.dps = int(entry) +1
         #condition for input error
         except:
                print("Looks like you did not enter an integer!")
                continue
         #execute and print result
         else:
              print(mp.pi)
              continue

祝你好运!