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 :)
There are essentially 3 different methods to calculate pi to many decimals. One of the oldest is to use the power series expansion of atan(x) = x - x^3/3 + x^5/5 - ... together with formulas like pi = 16*atan(1/5) - 4*atan(1/239). This gives about 1.4 decimals per term.
π rounded to 2 decimal places is 3.14 (3.141… is closer to 3.14 than to 3.15).
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 package
>>> from mpmath import mp
>>> mp.dps = 20 # set number of digits
>>> print(mp.pi)
3.1415926535897932385
Using np.pi
gives the wrong result
>>> format(np.pi, '.20f')
3.14159265358979311600
Compare to the true value:
3.14159265358979323846264338327...
Why not just format
using number_of_places
:
''.format(pi)
>>> format(pi, '.4f')
'3.1416'
>>> format(pi, '.14f')
'3.14159265358979'
And more generally:
>>> number_of_places = 6
>>> '{:.{}f}'.format(pi, number_of_places)
'3.141593'
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 initial number_of_digits
entered by the user is never used. It is instead being replaced by the iteratee values from the pi
string.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With