6

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?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Joan Venge
  • 315,713
  • 212
  • 479
  • 689
  • What version of Python is this? I tried `pow(-.6, 1.79)` in Python 3.2 and got a complex result. – Free Monica Cellio Feb 01 '12 at 03:13
  • @FreeMonicaCellio the built-in `pow` does that, as does `**` (with appropriate parentheses), but `math.pow` from the standard library reports an exception. Confusingly, both `pow`s describe themselves as ``, but they are not the same. – Karl Knechtel Jan 11 '23 at 03:14

3 Answers3

7

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.

wim
  • 338,267
  • 99
  • 616
  • 750
4

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)
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
0
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.
Jason Sundram
  • 12,225
  • 19
  • 71
  • 86
cola
  • 12,198
  • 36
  • 105
  • 165