简体   繁体   中英

Why is the square root of a negative number not purely imaginary in Python?

When I evaluate (-1)**0.5 in Python, the result is (6.123233995736766e-17+1j) . What is this number, and how can I get just 1j as the result?

6.123233995736766e-17 is a very small number expressed in scientific notation - written as a decimal, this number is 0.00000000000000006123233995736766 . The correct real part of the result should be exactly zero, so the result is wrong, but only slightly wrong. Generally, computations involving floating-point numbers do not give exact results; for an explanation, see Is floating point math broken?

If you want to compute complex square roots and guarantee that the square root of a negative real number is purely imaginary, you could write a function specifically to have this behaviour:

def my_sqrt(z):
    z = complex(z)
    if z.real < 0 and z.imag == 0:
        return 1j * (-z.real) ** 0.5
    else:
        return z ** 0.5

Examples:

>>> my_sqrt(-1)
1j
>>> my_sqrt(-2)
1.4142135623730951j
>>> my_sqrt(9)
(3+0j)
>>> my_sqrt(-3 + 4j)
(1.0000000000000002+2j)

Note that due to floating-point inaccuracies, some results will be slightly wrong, for example the true square root of -3 + 4j should be 1 + 2j . If you want exact results in all circumstances where this is possible, consider learning SymPy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM