[Python-ideas] complex number and fractional exponent
Mark Dickinson
dickinsm at gmail.com
Sun Jan 27 12:04:17 CET 2013
On Sat, Jan 26, 2013 at 9:22 PM, Oscar Benjamin
<oscar.j.benjamin at gmail.com> wrote:
> Why does cmath.sqrt give a different value from the __pow__ version?
>
> ~$ python3
> Python 3.2.3 (default, Oct 19 2012, 19:53:16)
> [GCC 4.7.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
>>>> import cmath
>>>> cmath.sqrt(-1)
> 1j
>>>> (-1) ** .5
> (6.123031769111886e-17+1j)
Because they use different algorithms. pow(x, y) essentially computes
exp(y * log(x)). That involves a number of steps, any of which can
introduce small errors. cmath.sqrt can use a more specific (and
usually more accurate) algorithm. Moral: use cmath.sqrt and math.sqrt
for computing square roots, rather than x ** 0.5.
Mark
More information about the Python-ideas
mailing list