将复数值分配给 numpy 数组? [英] Assigning complex values to numpy arrays?
问题描述
这给出了预期的结果
x = random.rand(1) + random.rand(1)*1j打印 x.dtype打印 x, x.real, x.imag
这有效
C = zeros((2,2),dtype=complex)C[0,0] = 1+1j打印 C
但是如果我们把它改成
C[0,0] = 1+1j + x
我收到类型错误:无法将复杂转换为浮点数".
如果我们现在省略显式的 dtype = complex
,我会得到ValueError: setting an array element with a sequence".
有人可以解释发生了什么,以及如何做到这一点而不会出错?我迷路了.
要将复杂的 x
或 x + something
插入到 C
中,您显然需要把它当作一个数组来对待,所以要么索引到 x
中,要么将它分配给 C
的一个切片:
看起来 NumPy 没有正确处理这种情况.考虑提交错误报告.
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".
Can someone explain what's going on, and how to do this without errors? I'm lost.
To insert complex x
or x + something
into C
, you apparently need to treat it as if it were an array, so either index into x
or assign it to a slice of 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 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!