如何计算“ComplexWarning:将复数转换为实数会丢弃虚部”?

2024-06-02 08:27:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用一个包含复杂项的矩阵来构造一个新的矩阵,但是它给了我警告

"ComplexWarning: Casting complex values to real discards the imaginary part".

因此,新矩阵的条目都是实数。如何使所有的条目都保持其虚部?在

这是包含我原始代码的图像

This is the image containing my original code


Tags: theto代码警告条目矩阵realvalues
2条回答

您可以尝试使用numpy来使用数组构造函数从矩阵_1创建一个新矩阵。这样就可以指定您使用的是带有dtype的复数。像这样的方法应该可以做到:

mat_ = np.array(matrix_1[:,ll,ll,:],dtype = "complex_")

一些我用来确保:

import numpy as np

abc = np.array([[1+1j,2+2j,3+3j],[4+4j,5+5j,6+6j],[7+7j,8+8j,9+9j]],dtype = "complex_") # initial
print(abc)
abc2 = np.array(abc[1:,:1],dtype = "complex_") # post transformation
print(abc2)

我知道我在哪里发出这个警告。在

当我构造一个新的空矩阵时,我需要添加dtype=“complex”。在

例如

mat__ = np.zeros((k*nboxes,k*nboxes),dtype = 'complex_')

如果我们只写

^{pr2}$

然后做一些操作,比如用一个复矩阵来形成一个新的矩阵,然后这个新矩阵就会去掉虚部。在

相关问题 更多 >