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 :)
Why not just
format
usingnumber_of_places
:And more generally:
In your original approach, I guess you're trying to pick a number of digits using
number_of_places
as the control variable of the loop, which is quite hacky but does not work in your case because the initialnumber_of_digits
entered by the user is never used. It is instead being replaced by the iteratee values from thepi
string.The proposed solutions using
np.pi
,math.pi
, etc only only work to double precision (~14 digits), to get higher precision you need to use multi-precision, for example the mpmath packageUsing
np.pi
gives the wrong resultCompare to the true value:
Your solution appears to be looping over the wrong thing:
For 9 places, this turns out be something like:
Which loops three times, one for each "9" found in the string. We can fix your code:
But this still limits
n
to be less than thelen(str(math.pi))
, less than 15 in Python 2. Given a seriousn
, it breaks:To do better, we have to calculate PI ourselves -- using a series evaluation is one approach:
Now we can take on a large value of
n
: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.
Thanks for Reading.