Calculate Pi with Python
Last Updated :
11 Dec, 2023
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.
Python3
import math
print ( math.pi )
|
Finding PI Value Using NumPy
In this method, we will use numpy.pi methods to calculate the pi value.
Python3
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.
Python3
k = 1
s = 0
for i in range ( 1000000 ):
if i % 2 = = 0 :
s + = 4 / k
else :
s - = 4 / k
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
from math import acos
def printValueOfPi():
pi = round ( 2 * acos( 0.0 ), 3 )
print (pi)
if __name__ = = "__main__" :
printValueOfPi()
|
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.
Python3
import math
print (math.radians( 180 ))
|
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.
Python3
import math
def calculate_circle_area(radius):
area = math.pi * radius * * 2
return area
radius = 5.0
area = calculate_circle_area(radius)
print (f "The area of a circle with radius {radius} is: {area}" )
|
OutputThe area of a circle with radius 5.0 is: 78.53981633974483
Share your thoughts in the comments
Please Login to comment...