提高到1/3可获得复数

编程入门 行业动态 更新时间:2024-10-22 16:30:56
本文介绍了提高到1/3可获得复数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我无法理解以下输出.我希望Numpy返回-10(或近似值).为什么是复数?

I cannot understand the following output. I would expect Numpy to return -10 (or an approximation). Why is it a complex number?

print((-1000)**(1/3.))

脾气暴躁的答案

(5+8.660254037844384j)

Numpy官方教程说答案是nan.您可以在本教程的中间找到它.

Numpy official tutorial says the answer is nan. You can find it in the middle of this tutorial.

推荐答案

您正在对常规的Python标量而不是numpy数组求幂.

You are exponentiating a regular Python scalar rather than a numpy array.

尝试一下:

import numpy as np print(np.array(-1000) ** (1. / 3)) # nan

区别在于numpy不会自动将结果提升为复杂类型,而将Python 3标量提升为复杂值(在Python 2.7中,您只会得到ValueError).

The difference is that numpy does not automatically promote the result to a complex type, whereas a Python 3 scalar gets promoted to a complex value (in Python 2.7 you would just get a ValueError).

如上面给出的@jonrsharpe链接中所述,负数具有多个多维数据集根.要获得所需的根,可以执行以下操作:

As explained in the link @jonrsharpe gave above, negative numbers have multiple cube roots. To get the root you are looking for, you could do something like this:

x = -1000 print(np.copysign(np.abs(x) ** (1. / 3), x)) # -10.0

更新1

马克·狄金森(Mark Dickinson)对于问题的根本原因是绝对正确的-由于舍入错误,1. / 3与第三位不完全相同,因此x ** (1. / 3)与x的立方根并不完全相同

Update 1

Mark Dickinson is absolutely right about the underlying cause of the problem - 1. / 3 is not exactly the same as a third because of rounding error, so x ** (1. / 3) is not quite the same thing as the cube root of x.

更好的解决方案是使用 scipy.special.cbrt ,它计算精确"多维数据集根而不是x ** (1./3):

A better solution would be to use scipy.special.cbrt, which computes the 'exact' cube root rather than x ** (1./3):

from scipy.special import cbrt print(cbrt(-1000)) # -10.0

更新2

还值得注意的是版本的numpy> = 0.10.0 将基于 C99 cbrt函数.

Update 2

It's also worth noting that versions of numpy >= 0.10.0 will have a new np.cbrt function based on the C99 cbrt function.

更多推荐

提高到1/3可获得复数

本文发布于:2023-11-30 03:22:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648553.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:复数   提高到   可获得

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!