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

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • 4
    FWIW, works for me… – deceze May 03 '21 at 13:19
  • Your hand calculator is probably interpreting your input as `-(0.0806 ** 0.0806)`, rather than `(-0.0806) ** 0.0806` - which indeed has no answer among the real numbers. If you want to get the complex result in Python, you need to convert at least one of the arguments to `pow()` to a complex number - either add `0j` to one of them, or apply `complex()` to it. – jasonharper May 03 '21 at 13:28
  • Works fine with builtin pow. If you import pow from math, than it'll raise this error. Could you clarify the question? Do you do that import? – STerliakov May 03 '21 at 13:30
  • @jasonharper in python 3.9.1 this just works, without the `complex()` or `0j` modification. @stoopidhooman should specify what version of python he is using. On python 2.7.x in some online IDE I get a slightly different `ValueError: negative number cannot be raised to a fractional power`. – Kraay89 May 03 '21 at 13:34
  • I am using 3.8.3 – Stoopidhooman May 03 '21 at 13:41
  • Actually it is not working SUTerliakov, now it raises TypeError: can't convert complex to float – Stoopidhooman May 03 '21 at 13:46

1 Answers1

0

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

H. Pope
  • 123
  • 13