Search code examples
pythonmathvalueerrorpow

Program throws value error when I exponentiate, Python 3


from math import pow
    
x = -0.0806
power_number = 0.0806
    
rezultat = pow(float(x), float(power_number))

Picture with info

After that it throws ValueError: math domain error! Why is it throwing error, I know that when negative number is raised to fractional power and denominator is even then it throws error because it is imaginary number. When i change x in this example to be positive it outputs valid result but why would it throw error can someone explain from math perspective. Why can't I raise negative decimal number to a decimal number? (btw. they are both same x and power_number only x is negative)

My guess it is just python thinking there is only 1 way exponentiation should be done, so maybe i just cheat it by making the x positive then switching the result back to negative. But if there is other way it would help.

Handheld calculator give valid output and are not throwing Math Error when I input x and power_number from picture...


Solution

  • From: negative pow in python

    A negative number raised to a float power will be a complex number. To account for this what you could do is add 0j to the exponent to let python know you want an complex, and then only take the real part.

    The below code should do what you want.

    x = -0.0806
    power_number = 0.0806
    
    rezultat = pow(float(x), float(power_number) + 0j).real