将pi打印到多个小数位

时间:2017-07-31 12:58:56

标签: python pi

w3资源的挑战之一是将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而不考虑任何输入。任何帮助都会很棒:)

8 个答案:

答案 0 :(得分:9)

为什么不只是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作为循环的控制变量来选择一些数字,这非常hacky但在你的情况下不起作用,因为初始{{用户输入的1}}从未使用过。而是由number_of_digits字符串中的iteratee值替换。

答案 1 :(得分:6)

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

>>> 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...

答案 2 :(得分:1)

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

#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

祝朋友好运!

答案 3 :(得分:0)

你的解决方案似乎是错误的做法:

for number_of_places in fraser:

对于9个地方,结果如下:

for "9" in "3.141592653589793":

哪个循环三次,每次一个&#34; 9&#34;在字符串中找到。我们可以修复您的代码:

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 2中小于15. {鉴于严重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
> 

答案 4 :(得分:0)

这个问题已经有了有用的答案,我只想分享我为相同目的创建程序的方式,这与问题中的程序非常相似。

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)

感谢阅读。

答案 5 :(得分:0)

例如mpmath

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

答案 6 :(得分:0)

为什么不只使用:

import numpy as np

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

答案 7 :(得分:0)

这是我所做的,确实很基础,但是可以工作(最多15个小数位):

const str = "<span> list: <mat> </span> && <span> see: how much <mat> </span> && <span> with: <mat> = '<pok>'</span>";
const escape = str => str
  .replace(/</g, '&lt')
  .replace(/>/g, '&gt');

const result = str.replace(
  /<[^>]+>/g,
  match => (match === '<span>' || match === '</span>') ? match : escape(match)
);
console.log(result);