问题描述
Python 3.4 似乎使用 **
运算符随机决定是否返回数字的实根或复根:
有没有办法确保在立方体生根时得到真正的根而不是复杂的根?
在第二种情况下,实际上首先计算立方根,然后应用减号,因此是真正的根.
即 -1636.281**(1/3)
变成 -(1636.281**(1/3))
.您也可以使用类似的逻辑来获得实数三次方根.
但实际上,在做负数的三次方根时,你总是在 python 中得到复数.
>>>-1636.281**(1/3)-11.783816270504108>>>(-1636.281)**(1/3)(5.891908135252055+10.205084243784958j)如果你想要实数,你可以添加如下代码 -
def 立方体(x):如果 x >= 0:返回 x**(1/3)elif x
Python 3.4 seemingly randomly decides whether it returns the real or complex root of a number using the
**
operator:
>>> (863.719-2500)
-1636.281
>>> -1636.281**(1/3)
-11.783816270504108
>>> (863.719-2500)**(1/3)
(5.891908135252055+10.205084243784958j)
Is there a way to ensure you get the real root when cube rooting rather than one of the complex ones?
解决方案
In the second case actually the cube root is getting evaluated first then the minus sign is getting applied, hence the real root.
That is
-1636.281**(1/3)
becomes -(1636.281**(1/3))
. And you can use a similar logic to get the real cubic roots as well.
But actually, when doing cubic root of negative numbers you always get complex numbers in python.
>>> -1636.281**(1/3)
-11.783816270504108
>>> (-1636.281)**(1/3)
(5.891908135252055+10.205084243784958j)
If you want real numbers you can add code like -
def cube(x):
if x >= 0:
return x**(1/3)
elif x < 0:
return -(abs(x)**(1/3))
这篇关于如何在Python3中获得负数的实数立方根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!