Search code examples
pythonpython-3.xmathcomplex-numbers

Exponential operator in Python - Giving different result with using variables and with using direct values


We are using exponential operator as below with assigning values to variables:

>>> a = -1.5
>>> b = 0.44
>>> c = (a ** b)
>>> c
(0.22397855343551604+1.1741366953411416j)

If we use direct values in the exponential operator the result is different:

>>> d = (-1.5 ** 0.44)
>>> d
-1.195308902228074

We need the second output using the variables.


Solution

  • The problem is that - has a lower precedence than **, so the expression -1.5 ** 0.44 is actually parsed as if it is -(1.5 ** 0.44).

    To get the correct result, you should write (-1.5) ** 0.44.

    >>> -1.5 ** 0.44
    -1.195308902228074
    >>> -(1.5 ** 0.44)
    -1.195308902228074
    >>> (-1.5) ** 0.44
    (0.22397855343551604+1.1741366953411416j)
    

    The result -1.195308902228074 is actually incorrect mathematically, but if you really want the incorrect result after assigning the numbers to variables, then you can use abs and math.copysign:

    >>> a = -1.5
    >>> b = 0.44
    >>> import math
    >>> math.copysign(abs(a) ** b, a)
    -1.195308902228074