Python-根据用户指定的数量舍入PI的值

时间:2016-07-02 15:19:52

标签: python

我的代码:

import math
def CalPI(precision):
    answer = round((math.pi),precision)
    return answer

precision=raw_input('Enter number of digits you want after decimal:')

try:
    roundTo=int(precision)
    print CalPI(roundTo)

except:
    print 'Error'

当我运行此代码时,我得到的输出最大值只能达到11位小数。 但是我想根据用户给出的输入生成输出。

This is my output snip:

谁能告诉我哪里出错了?

提前谢谢!

2 个答案:

答案 0 :(得分:2)

如果您在打印中使用repr,您将拥有15位数:3.141592653589793。

如果您想要更多数字(直到50),请使用

nb_digits = 40
print(format(math.pi, '.%dg' % nb_digits))

(感谢Stefan的精确度:)但正如他再次声明:不要相信数字15之后的数字,所以1000位数的程序是最好的。)

对于更多数字,请像在这里一样自己计算:

1000 digits of pi in python

答案 1 :(得分:0)

"""
Math provides fast square rooting
Decimal gives the Decimal data type which is much better than Float
sys is needed to set the depth for recursion.
"""
from __future__ import print_function
import math, sys
from decimal import *
getcontext().rounding = ROUND_FLOOR
sys.setrecursionlimit(100000)

python2 = sys.version_info[0] == 2
if python2:
    input = raw_input()

def factorial(n):
    """
    Return the Factorial of a number using recursion
    Parameters:
    n -- Number to get factorial of
    """
    if not n:
        return 1
    return n*factorial(n-1)


def getIteratedValue(k):
    """
    Return the Iterations as given in the Chudnovsky Algorithm.
    k iterations give k-1 decimal places. Since we need k decimal places
    make iterations equal to k+1

    Parameters:
    k  -- Number of Decimal Digits to get
    """
    k = k+1
    getcontext().prec = k
    sum=0
    for k in range(k):
        first = factorial(6*k)*(13591409+545140134*k)
        down = factorial(3*k)*(factorial(k))**3*(640320**(3*k))
        sum += first/down 
    return Decimal(sum) 

def getValueOfPi(k):
    """
    Returns the calculated value of Pi using the iterated value of the loop
    and some division as given in the Chudnovsky Algorithm
    Parameters:
    k -- Number of Decimal Digits upto which the value of Pi should be calculated
    """
    iter = getIteratedValue(k)
    up = 426880*math.sqrt(10005)
    pi = Decimal(up)/iter 

    return pi

def shell():
    """
    Console Function to create the interactive Shell.
    Runs only when __name__ == __main__ that is when the script is being called directly
    No return value and Parameters
    """
    print ("Welcome to Pi Calculator. In the shell below Enter the number of digits upto which the value of Pi should be calculated or enter quit to exit")

    while True:
        print (">>> ", end='')
        entry = input()
        if entry == "quit":
            break
        if not entry.isdigit():
            print ("You did not enter a number. Try again")
        else:
            print (getValueOfPi(int(entry)))

if __name__=='__main__':
    shell()