Why does math.pow result in ValueError: math domain error?

Question:

Here is the code:

exp = 1.79
def calc(t):
    return pow(t - 1, exp)

The input values of t range from 0 to 1 (e.g. 0.04). This code throws a “math domain exception,” but I’m not sure why.

How can I solve this?

Asked By: Joan Venge

||

Answers:

If t ranges from 0 to 1, then t - 1 ranges from -1 to 0. Negative numbers cannot be raised to a fractional power, neither by pow builtin nor math.pow.

Answered By: wim

Negative numbers raised to a fractional exponent do not result in real numbers. You will have to use cmath if you insist on calculating and using them, but note that you will need some experience in complex numbers in order to make use of the result.

>>> cmath.exp(cmath.log(0.04 - 1) * 1.79)
(0.7344763337664206-0.5697182434534497j)
exp = 1.79
def calc(t):
    return pow(t - 1, exp)

print calc(1.00) # t-1 is 0, there will be no error.
print calc(0.99) # t-1 is negative, will raise an error.
Answered By: shibly