Python Program to Find Area of a Circle
The task of calculating the Area of a Circle in Python involves taking the radius as input and applying the mathematical formula for the area of a circle.
Area of a circle formula:
Area = pi * r2
where,
- π (pi) is a mathematical constant approximately equal to 3.14159.
- r is the radius of circle.
For example, if r = 5, the area is calculated as Area = 3.14159 × 5² = 78.53975.
Using math.pi
math module provides the constant math.pi, representing the value of π (pi) with high precision. This method is widely used in mathematical calculations and is considered a standard approach in modern Python programming.
import math
r = 5 # radius
area = math.pi * (r ** 2)
print(area)
Output
78.53981633974483
Explanation: area is calculated using the formula math.pi * (r ** 2), where "r ** 2" squares the radius, and math.pi ensures high precision value for π.
Using math.pow()
math.pow() function is optimized for power calculations, making it more readable when dealing with complex exponents.
import math
r = 5 # radius
area = math.pi * math.pow(r, 2)
print(area)
Output
78.53981633974483
Explanation: math.pi * math.pow(r, 2), where math.pow(r, 2) raises the radius to the power of 2, math.pi ensures the use of a precise value of π.
Using numpy.pi
numpy library is designed for high-performance numerical computations and "numpy.pi" provides a precise value of π.
import numpy as np
r = 5 # radius
area = np.pi * (r ** 2)
print(area)
Output
78.53981633974483
Explanation: np.pi * (r ** 2), where np.pi provides a high-precision value of π and r ** 2 squares the radius.
Using hardcoded pi value
This is a simple and traditional approach where the value of π is manually set as a constant . It is often used in basic programs or quick prototypes where precision is not critical.
PI = 3.142
r = 5 # radius
area = PI * (r * r)
print(area)
Output
78.55
Explanation: area is then calculated using the formula PI * (r * r), where "r * r" squares the radius.