0
0 == ((-1)**.5).real

... is False in python 3.5.1, whereas:

0 == complex(0,1).real

... is True. how are these two cases handled differently? when do the zero-detecting features of the float class work and when do they not?

Aaron Brick
  • 236
  • 2
  • 11
  • 2
    `(-1)**0.5 -> (6.123233995736766e-17+1j)` on my machine, I'd assume because of [floating point math](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Tadhg McDonald-Jensen May 24 '16 at 00:40

2 Answers2

6
>>> (-1)**0.5
(6.123233995736766e-17+1j)

That's all there is to it - due to floating-point vagaries, the real part of the computed result isn't exactly zero. But in your other case it is:

>>> complex(0,1).real
0.0

By the way, ** invokes a general-purpose exponentiation routine, which adds several layers of floating-point roundoff errors under the covers. If you know you want a square root, it's better to use a square root function:

>>> import cmath
>>> cmath.sqrt(-1)
1j
Tim Peters
  • 67,464
  • 13
  • 126
  • 132
2

The fractional power is computed -- simplifying somewhat -- as r cis theta. Since theta (pi) cannot be exactly represented as a binary fraction, the result is not exactly what you'd expect from hand calculation. There are various "equal within a tolerance" functions you can apply to work around this.

Prune
  • 76,765
  • 14
  • 60
  • 81