Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python math domain error when using pow

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?

like image 681
Joan Venge Avatar asked Dec 28 '22 06:12

Joan Venge


2 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.

like image 74
wim Avatar answered Dec 31 '22 12:12

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)
like image 40
Ignacio Vazquez-Abrams Avatar answered Dec 31 '22 13:12

Ignacio Vazquez-Abrams