The area of a circle can be calculated using its radius and the mathematical constant π. Area of a circle formula:
Area = π × r²
where:
- π (pi) is approximately 3.14159.
- r is the radius of the circle.
For example, if r = 5, the area is approximately 78.5398.
Using math.pi
The math module provides math.pi, which represents the value of π with high precision.
import math
r = 5 # radius
area = math.pi * (r ** 2)
print(area)
Output
78.53981633974483
Explanation:
- math.pi provides the value of π.
- r ** 2 calculates the square of the radius.
- math.pi * (r ** 2) applies the area formula.
- area stores the calculated value
Using math.pow()
The math.pow() function can be used to raise the radius to the power of 2.
import math
r = 5 # radius
area = math.pi * math.pow(r, 2)
print(area)
Output
78.53981633974483
Explanation:
- math.pow(r, 2) calculates the square of the radius.
- math.pi provides the value of π.
- Multiplying them gives the area of the circle.
Using numpy.pi
NumPy provides numpy.pi for mathematical calculations involving π. This approach is useful when NumPy is already being used for numerical operations.
import numpy as np
r = 5 # radius
area = np.pi * (r ** 2)
print(area)
Output
78.53981633974483
Explanation:
- np.pi provides the value of π.
- r ** 2 calculates the square of the radius.
- np.pi * (r ** 2) calculates the area.
Using hardcoded pi value
The value of π can also be stored manually in a variable. This approach provides an approximation and is less precise than using math.pi or numpy.pi.
PI = 3.142
r = 5 # radius
area = PI * (r * r)
print(area)
Output
78.55
Explanation:
- PI stores an approximate value of π.
- r ** 2 calculates the square of the radius.
- PI * (r ** 2) calculates the approximate area.