Python中多维数据集根的值错误 [英] Wrong value for cube root in Python
问题描述
在 repl.it 和Windows控制台中都使用Python 3.5时,我得到了错误的答案立方根.
Using Python 3.5 both at repl.it and the console in Windows, I get wrong answers for cube roots.
当输入为(-1)**(1/3)
时,
当它应该简单地为-1时,我得到复数(0.5000000000000001 + 0.8660254037844386j)作为答案.此根下的任何负值似乎都会产生复杂的结果.
When the input is (-1)**(1/3)
,
I get the complex number (0.5000000000000001+0.8660254037844386j) as the answer when it should simply be -1. Any negative value under this root seems to give a complex result.
我做错什么了吗?
推荐答案
带负底数的幂通常涉及复数,因此Python在看到负底数时会切换为复数.这样的幂运算通常是多值的,Python并不总是返回您可能期望的值.
Exponentiation with negative bases typically involves complex numbers, so Python switches to complex numbers when it sees the negative base. Such exponentiation is typically mutlivalued, and Python doesn't always return the value you might expect.
对于带有实数底数的1/3次幂的特殊情况,您可以编写如下函数:
For the special case of the 1/3 power with real bases, you could write a function like this:
def cubeRoot(x):
if x >= 0:
return x**(1/3)
else:
return -(-x)**(1/3)
这将给出预期的真实多维数据集的根.
Which will give the expected real cube root.
这篇关于Python中多维数据集根的值错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!