import math
print(math.pow(2,3)) # 8.0
print(math.pow(2,-3)) # 0.125
print(math.pow(-2,-3)) # -0.125
print(math.pow(-2,3)) # -8.0
Using floats
import math
print(math.pow(2.2,3)) # 10.648000000000003
print(math.pow(2.2,-3)) # 0.09391435011269719
x is negative, and y is not an integer then pow(x, y) is undefined and raise ValueError.
print(math.pow(-2,3.3))
print(math.pow(-2,3.3))
Above code will generate error
import math
try:
print(math.pow(-2, 0.5))
# Raises ValueError because square root of
#a negative number is undefined
except ValueError as e:
print(e)
Output
math domain error
import math
print(2 ** 3) # Output: 8 (int)
print(math.pow(2, 3)) # Output: 8.0 (float)
One common use of math.pow() is in financial calculations like compound interest. The formula is:
import math
# Compound Interest Formula
principal = 1000 # Initial amount
rate = 5 / 100 # Annual interest rate (5%)
time = 10 # Number of years
# Calculating final amount using math.pow()
amount = principal * math.pow(1 + rate, time)
print(f"Final amount: {amount:.2f}") # Output: Final amount: 1628.89
In this example, the math.pow() function is used to calculate the exponential growth over 10 years.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.