如何在Python3中获得负数的实数立方根? [英] How to get the real cube root of a negative number in Python3?

查看:43
本文介绍了如何在Python3中获得负数的实数立方根?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 3.4 似乎使用 ** 运算符随机决定是否返回数字的实根或复根:

<预><代码>>>>(863.719-2500)-1636.281>>>-1636.281**(1/3)-11.783816270504108>>>(863.719-2500)**(1/3)(5.891908135252055+10.205084243784958j)

有没有办法确保在立方体生根时得到真正的根而不是复杂的根?

解决方案

在第二种情况下,实际上首先计算立方根,然后应用减号,因此是真正的根.

-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 <0:返回 -(abs(x)**(1/3))

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中获得负数的实数立方根?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆