# Power of results in nan

Hi, I’m getting nan when I calculate an exponent like this:

``````    a, b, c, d, g = popt

bas = (1/(((d - a)/(d - y))**(1/g) - 1))
exp = ((b - 1)/b)

print("bas: ", bas )  # ----------> print and copy result
print("exp: ", exp )

calc1 = bas**exp
calc2 = -5.165486691184695**0.7268879959898965 # <--------- paste result

print("calc1: ", calc1) # nan
print("calc2: ", calc2) # correct result
``````

I hope the code is readable… I get the correct result when I write the numbers in the like for calc2. When I use the variables holding the same values I get nan. What am I doing wrong?

Edit, I forgot to mention that I get a runtime warning: RuntimeWarning: invalid value encountered in scalar power

Can you give us some example values for these variables?

A NaN (or an exception) is the expected result when raising a negative value to a fractional power; there isn’t a single obvious mathematical meaning for (for example) `(-2.0)**0.25`.

That’s because `calc1` and `calc2` are doing different things, thanks to operator precedence subtleties. In `calc1`, you’re computing

``````(-5.165486691184695)**0.7268879959898965
``````

which is mathematically ill-defined (or at the very least, ambiguous). In `calc2`, you’re instead computing

``````-(5.165486691184695**0.7268879959898965)
``````

which is perfectly well-defined, since you’re now raising a positive real number to a fractional power.

1 Like

Except of course that Python produces neither a NaN nor an exception, but instead gives a complex number (which is another possible interpretation):

``````>>> (-5.165486691184695)**0.7268879959898965
(-2.1572199466523343+2.4956530319240686j)
``````

But without knowing anything about your context, I’m still going to guess that that complex result is not what you want either. It seems likely that there’s either an error in the formula you’re using, or you’re using that formula on values that are out of range for the intended use.

1 Like