Recap that pi is an essential constant when doing mathematical calculations and we can easily access pi using the numpy module in Python. It is simplicity itself:
import numpy as np
print(np.pi)
The output is:
Thus, np.pi is your constant referring to the ratio of a circle’s circumference to its diameter.
You should remember to prefix the “pi” with the module you are taking it from: in our case, numpy. To make your program more readable for yourself, you can do:
import numpy as np
pi = np.pi
print(pi)
Here we are creating a variable (also called “pi”) in our program and initializing it to numpy’s pi. The output is the same:
Calculating the area of a circle
We can use pi in a function that calculates the area of a circle:
import numpy as np
def area(radius):
return(np.pi*radius*radius)
r = 7
a = area(r)
print(r,a)
Here we are simply writing the formula for the area of a circle in the function area that takes a radius as input. The output prints the radius of a sample circle (7 units) and its area (in units squared):
Calculating the circumference of a circle
Similarly, we can compute the circumference of a circle like so:
import numpy as np
def area(radius):
return(np.pi*radius*radius)
def circumference(radius):
return(2*np.pi*radius)
r = 7
a = area(r)
c = circumference(r)
print(r,a,c)
The circumference formula simply calculates the diameter times pi to find the length of the circumference. The output is:
7 153.93804002589985 43.982297150257104
Converting degrees to radians
Another use of pi is to convert degrees to radians. Recap that “pi” radians is 180 degrees, so we can write a function like so:
import numpy as np
def deg_to_rad(d):
return(d*np.pi/180)
angle = 360
print(angle,deg_to_rad(angle))
Here we simply multiply the input degrees by pi/180 to obtain the equivalent angle in radians. The output is:
Converting radians to degrees
Similarly we can write the inverse function to convert radians to degrees by simply multiplying the input radians by 180/pi:
import numpy as np
def rad_to_deg(r):
return(r*180/np.pi)
radians = np.pi
print(radians,rad_to_deg(radians))
The output in the above case will be:
To summarize, pi is an essential constant for geometric calculations and we have easy access to it using Python numpy. Using just one expression (np.pi) we can access its value and use it in any formulaic calculations.
Write to us to tell us how you used numpy.pi()!
Interested in more things Python? Checkout our post on Python queues. Also see our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!