1

Is there any difference between the infinities returned by the math module and cmath module?

Does the complex infinity have an imaginary component of 0?

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
Alec
  • 8,529
  • 8
  • 37
  • 63

1 Answers1

4

Any difference?

No, there is no difference. According to the docs, both math.inf and cmath.inf are equivalent to float('inf'), or floating-point infinity.

If you want a truly complex infinity that has a real component of infinity and an imaginary component of 0, you have to build it yourself: complex(math.inf, 0)

There is, however, cmath.infj, if you want 0 as a real value and infinity as the imaginary component.

Constructing imaginary infinity

As others have pointed out math.inf + 0j is a bit faster than complex(math.inf, 0). We're talking on the order of nanoseconds though.

Alec
  • 8,529
  • 8
  • 37
  • 63
  • Alternatively, `complex(math.inf, 0)` can be constructed as `math.inf + 0j` or `complex("inf")`. Based on some back of the envelope timing with `timeit`, `math.inf + 0j` is the fastest by a noticable margin (~60 ns, versus 90 ns and 120 ns for `complex("inf")` and `complex(math.inf, 0)`, respectively.) – Brian61354270 Feb 05 '23 at 01:17
  • @Brian noted in edit – Alec Feb 05 '23 at 01:43
  • `complex(math.inf)` is enough; imaginary part is by default zero (and real too, if you use just `complex()`). Anyway, it'd be even better to tweak your program so it handles `float`s, `int`s (or [other types](https://docs.python.org/3/library/numbers.html)) as well instead of requiring `complex` instances. All of the number types have `imag` part, equal to 0 in case of real numbers. – Trang Oul Mar 09 '23 at 13:34