Print pi to a number of decimal places

Viewed 43618

One of the challenges on w3resources is to print pi to 'n' decimal places. Here is my code:

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)

For whatever reason, it automatically prints pi without taking into account of any inputs. Any help would be great :)

8 Answers

For example the mpmath package

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

Great answers! there are so many ways to achieve this. Check out this method I used below, it works any number of decimal places till infinity:

#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

Good luck Pal!

As this question already has useful answers, I would just like to share how i created a program for the same purpose, which is very similar to the one in the question.

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)

Thanks for Reading.

Why not just use:

import numpy as np

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

This is what I did, really elementary but works (max 15 decimal places):

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')
Related