Python 将复数值分配给 numpy 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22016847/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:04:53  来源:igfitidea点击:

Assigning complex values to numpy arrays?

pythonarraysnumpy

提问by gibson

This gives the expected result

这给出了预期的结果

x = random.rand(1) + random.rand(1)*1j
print x.dtype
print x, x.real, x.imag

and this works

这有效

C = zeros((2,2),dtype=complex)
C[0,0] = 1+1j
print C

but if we change it to

但是如果我们把它改成

C[0,0] = 1+1j + x

I get "TypeError: can't convert complex to float".

我收到“类型错误:无法将复杂转换为浮点数”。

If we now omit the explicit dtype = complex, I get "ValueError: setting an array element with a sequence".

如果我们现在省略显式dtype = complex,我会得到“ValueError:使用序列设置数组元素”。

Can someone explain what's going on, and how to do this without errors? I'm lost.

有人可以解释发生了什么,以及如何做到这一点而不会出错?我迷路了。

采纳答案by Fred Foo

To insert complex xor x + somethinginto C, you apparently need to treat it as if it were an array, so either index into xor assign it to a slice of C:

要插入 complexxx + somethinginto C,您显然需要将其视为一个数组,因此要么索引到x要么将其分配给 的切片C

>>> C
array([[ 0.+0.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j]])
>>> C[0, 0:1] = x
>>> C
array([[ 0.47229555+0.7957525j,  0.00000000+0.j       ],
       [ 0.00000000+0.j       ,  0.00000000+0.j       ]])
>>> C[1, 1] = x[0] + 1+1j
>>> C
array([[ 0.47229555+0.7957525j,  0.00000000+0.j       ],
       [ 0.00000000+0.j       ,  1.47229555+1.7957525j]])

It looks like NumPy isn't handling this case correctly. Consider submitting a bug report.

看起来 NumPy 没有正确处理这种情况。考虑提交错误报告。

回答by Lenka42

Actually, none of the proposed solutions worked in my case (Python 2.7.6, NumPy 1.8.2). But I've found out, that change of dtypefrom complex(standard Python library) to numpy.complex_may help:

实际上,在我的案例(Python 2.7.6、NumPy 1.8.2)中,没有提出的解决方案有效。但我发现,dtypecomplex(标准 Python 库)更改为numpy.complex_可能会有所帮助:

>>> import numpy as np
>>> x = 1 + 2 * 1j
>>> C = np.zeros((2,2),dtype=np.complex_)
>>> C
array([[ 0.+0.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j]])
>>> C[0,0] = 1+1j + x
>>> C
array([[ 2.+3.j,  0.+0.j],
       [ 0.+0.j,  0.+0.j]])