So you want to use pi or π in your python code, then you are in for a treat. We will be covering Python’s math.pi method of math module. We will also be looking at other ways to use pi(π), for instance, numpy.pi and scipy.pi methods of numpy and scipy libraries also do the same job, so we will examine when to use which respective methods.
Before jumping on the topic, let’s take a brief refresher on pi(π):
Pi or π(greek letter) is the ratio of a circle’s circumference to its diameter. It is an irrational number. In other words, the number of digits beyond the decimal point is infinite. 3.1415929 or 22/7 are two ways to write it. 14th March is observed as pi(π) day as 3, 1 & 4 are the significant digits of pi(π).
math.pi in Python
The math module provides the pi( π) constant value: numerous other constants and mathematical functions like power and logarithmic, trigonometric, special constants, etc.
Importing math.pi in Python
# to use it like math.pi
import math
# to use directly as pi
from math import pi
Examples of math.pi in Python
Example 1: Calculate a circle’s circumference while the radius is provided through an input stream.
import math
radius = int(input("Enter radius:"))
def cal_circum(radius:int):
return f"Circumference:{2*math.pi*radius} unit"
print(cal_circum(radius))
The formula gives the circumference of a circle- 2πR, where 2 and π are constants and R is the circle’s radius.
Example 2: Calculate the area of a circle while the radius is provided through an input stream.
import math
radius = int(input("Enter radius:"))
def cal_area(radius:int):
return f"Area:{math.pi*(radius**2)} unit sq."
print(cal_area(radius))
The formula gives the area of a circle – π*R2, where π is a constant and R is the circle’s radius.
math.pi precision
math.pi by default provides 15 places of precision for the value of pi. However, if you want to get a more precise pi(π) value, you can do so by using a decimal of Python’s standard library.
from decimal import *
import math
print(len(str(math.pi)))
getcontext().prec = 31
pi_precision = Decimal(22)/Decimal(7)
print(len(str(pi_precision)))
By excluding ‘3’ at the one’s place and the decimal, we get 15 and 30 digits of precision for math.pi and decimal, respectively.
The most accurate value of pi is 62,831,853,071,796 digits and was achieved by the University of Applied Sciences (Switzerland) in Chur, Switzerland, on 19 August 2021.
PI(π) without math module
You can use the value of pi(π) without using the math module. Let’s see how can we achieve this:
Using python’s convention
According to Python’s conventions, we can define constants using capital variable names. The only drawback is that anyone can easily modify the value.
PI = 22/7
print(PI)
Using pconst library
Another way is to use the pconst library, which helps create constant values that can’t be modified, just like other languages like c, c++, java, etc. Firstly you need to install the pconst library.
Code below, we try to change the constant value to 5, but the pconst library throws an error “Constant value of ‘PI’ is not editable”, thus preventing any changes. Pconst can be used to define our own constants, which we don’t want to be modified.
pip install pconst
from pconst import const
const.PI = 22/7
try:
const.PI = 5
except Exception as e:
print(const.PI)
print(e)
Using NumPy
If you want or work with arrays and matrices, the NumPy library is a clear choice. It has functions for working in the domain of linear algebra, Fourier transform, etc. It provides the constant pi(π). However, to use it, you must install it, depending on the case if you have Anaconda installed or not.
# if you have anaconda installed in your system
conda install numpy
# if you have only python installed
pip install numpy
Using SciPy
SciPy is a scientific computation library that uses NumPy underneath. SciPy stands for Scientific Python. It provides more utility functions for optimization, stats, and signal processing.
# if you have anaconda installed in your system
conda install scipy
# if you have only python installed
pip install scipy
FAQs on math.pi in Python
The math.pi is part of the built-in math library of Python, while the rest of the two have to be installed to make use of them. All three of them provide the same value. If you are looking to work on large data sets with numerous calculations, numpy or scipy are great options; otherwise, math.pi is the way to go.
Python Math PI is not Defined
To use pi in python, use: math.pi in your statement. It will give the value of pi as float – 3.141592653589793. If you’re getting the error message “math pi is not defined” in Python, it might be because you’re trying to use the constant pi without importing it from the math module.
Here’s an example of how to use pi correctly in Python:
import math
# Calculate the circumference of a circle of #radius 5
radius = 5
peri = 2 * math.pi * radius
print (peri)
In this example, we first import the math module using the import command. We then use the math.pi constant to calculate the circumference of a circle of radius 5. Prefixing pi with math tells Python to use the pi constant from the math module. Without this import statement, we would get the error message “NameError: name ‘pi’ is not defined”.
Math.pi vs np.pi
The value of pi with both numpy and math modules is above fifteen digits accuracy. It’s a float value and accessing the pi value from both modules fetches the same result.
The only difference is that math module doesn’t need any type of dependency but with numpy we need many additions.
In case, you are using numpy functionalities beforehand, go for np.pi.
FAQs
Just import the numpy library. It is a predefined function.
pip install numpy
import numpy as np
ans= np.pi
print(ans)
Conclusion
The math module of Python has many valuable tools; one of them is math.pi, which helps in mathematical computations involving pi(π). We looked at other ways to do the same task, but since math.pi is a built-in method of the standard library and hence doesn’t depend upon additional libraries, unlike numpy.pi and scipy.pi. We also looked at the default python’s convention for defining constant values and the pconst library as a good alternative.