complex("inf") ** 1 throws OverflowError

131 Views Asked by At

In Python 3.10.9, this example raises OverflowError: complex exponentiation:

complex("inf") ** 1

But this works, evaluating to (nan+nanj):

complex("inf") ** 2

Why does it work this way? Is there a bug to report?

1

There are 1 best solutions below

5
DataAngel On
import math

Infinity = complex(math.inf, 0) # or complex("inf") whichever returns (inf+0j)
print(Infinity)

result0 = Infinity ** 2
print(result0) # prints (nan+nanj)

result1 = Infinity ** 1
print(result1) # prints OverflowError: complex exponentiation

Hey Petr ! You got that because the complex class does not support the ** operator for infinite values.

The ** operator is used for exponentiation in Python. When applied to complex numbers, it raises the first number to the power of the second number. However, if either of the numbers is infinite, the result is undefined.

This programming behavior is defined by the IEEE 754 floating-point standard. In this standard, some rules govern the operations involving "inf" and "nan," and these rules are implemented consistently across most programming languages, including Python.

complex("inf") ** 1:

In this case, you are raising infinity to the power of 1. According to the rules, anything raised to the power of 1 remains unchanged. So, the result is inf (positive infinity). So python is unable to calculate it here and gives you a erro.

complex("inf") ** 2:

Here, you are squaring infinity. According to the rules, this results in a complex number with a real part of "inf" and an imaginary part of "nan"

However, Python chooses to represent undefined values with the special value NaN (Not a Number). Therefore, the result of complex(math.inf, 0) ** 2 is (nan+nanj).

So, there is no hidden bug here related to these operations.