Calculate Pi with Python
Pi is an irrational number having non-recurring decimal values. We commonly know Pi=3.14 or Pi=22/7, but it is just an approximation for our ease. In this article, we will see how to calculate PI with Python and also how to use PI in Python.
Calculate and Use PI in Python
Below are the ways by which we can calculate and use PI in Python:
- Using NumPy
- Using math module
- Using Leibniz's formula
- Using acos() methods
- Using Math.radians
Calculate PI in Python Using math module
Python has an inbuilt library named math we can simply import math and print the value of pi.
import math
print( math.pi )
Output
3.141592653589793
Finding PI Value Using NumPy
In this method, we will use numpy.pi methods to calculate the pi value.
import numpy
print( numpy.pi )
Output
3.141592653589793
Calculate PI Using Leibniz's formula
The formula is -
This series is never-ending, the more terms this series contains, the closer the value of X converges to Pi value.
In this example, the code calculates an approximation of pi using the Leibniz formula for pi, where positive and negative terms alternate. The loop iterates a million times, updating the sum (s
) with alternating positive and negative terms.
# Initialize denominator
k = 1
# Initialize sum
s = 0
for i in range(1000000):
# even index elements are positive
if i % 2 == 0:
s + = 4/k
else:
# odd index elements are negative
s -= 4/k
# denominator is odd
k += 2
print(s)
Output
3.1415916535897743
Calculating PI Using acos() methods.
In this example, the Python script uses the acos
function from the math
module to calculate the value of pi (π) up to 3 decimal places. The result is then rounded and printed.
# Python3 program to calculate the
# value of pi up to 3 decimal places
from math import acos
# Function that prints the
# value of pi upto N
# decimal places
def printValueOfPi():
# Find value of pi upto 3 places
# using acos() function
pi = round(2 * acos(0.0), 3)
# Print value of pi upto
# N decimal places
print(pi)
# Driver Code
if __name__ == "__main__":
# Function that prints
# the value of pi
printValueOfPi()
Output
3.142
Access Pi (π) Using Math.radians
In this example, the Python script uses the math.radians
function to convert 180 degrees to radians. The result, which represents the equivalent angle in radians, is then printed using the print
function.
import math
print(math.radians(180))
Output
3.141592653589793
Example: Calculating Area of a Circle Using math.pi
In this example, the Python script defines a function calculate_circle_area
that computes the area of a circle given its radius. The script then demonstrates the function by calculating and printing the area for a circle with a radius of 5.0.
import math
def calculate_circle_area(radius):
area = math.pi * radius**2
return area
# Example usage:
radius = 5.0
area = calculate_circle_area(radius)
print(f"The area of a circle with radius {radius} is: {area}")
Output
The area of a circle with radius 5.0 is: 78.53981633974483