为什么Python中负数的平方根不是纯虚数?
Why is the square root of a negative number not purely imaginary in Python?
当我在 Python 中计算 (-1)**0.5
时,结果是 (6.123233995736766e-17+1j)
。这个数字是多少,我怎样才能得到 1j
作为结果?
6.123233995736766e-17
是一个非常小的数字,用 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?
表示
如果您想计算复数平方根并保证负实数的平方根是纯虚数,您可以专门编写一个函数来实现此行为:
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
示例:
>>> my_sqrt(-1)
1j
>>> my_sqrt(-2)
1.4142135623730951j
>>> my_sqrt(9)
(3+0j)
>>> my_sqrt(-3 + 4j)
(1.0000000000000002+2j)
请注意,由于浮点数不准确,某些结果会略有错误,例如 -3 + 4j
的真实平方根应该是 1 + 2j
。如果您想在所有可能的情况下都获得准确的结果,请考虑学习 SymPy.
当我在 Python 中计算 (-1)**0.5
时,结果是 (6.123233995736766e-17+1j)
。这个数字是多少,我怎样才能得到 1j
作为结果?
6.123233995736766e-17
是一个非常小的数字,用 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?
如果您想计算复数平方根并保证负实数的平方根是纯虚数,您可以专门编写一个函数来实现此行为:
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
示例:
>>> my_sqrt(-1)
1j
>>> my_sqrt(-2)
1.4142135623730951j
>>> my_sqrt(9)
(3+0j)
>>> my_sqrt(-3 + 4j)
(1.0000000000000002+2j)
请注意,由于浮点数不准确,某些结果会略有错误,例如 -3 + 4j
的真实平方根应该是 1 + 2j
。如果您想在所有可能的情况下都获得准确的结果,请考虑学习 SymPy.