调用 qr_solve 时无法从复数创建 mpf [英] Cannot create mpf from a complex number when calling qr_solve
问题描述
我进行了以下导入:
from sympy.matrices import Matrix as sy_matrix
import sympy.mpmath as sy_mp
像这样创建我的矩阵:
sysMat = sy_matrix([[0.0]*sz1]*sz2)
resVec = sy_matrix([[0.0]]*sz2)
.Populate 然后用 python 复数(例如 1.0+1.0j)然后调用:
.Populate then with python complex numbers (eg 1.0+1.0j) and then call:
coeffVec = sy_mp.qr_solve(sysMat, resVec)
但是我得到以下异常:
File "..\RatSMat.py", line 69, in solve
self.coeffVec = sy_mp.qr_solve(self.sysMat, self.resVec)
File "C:\Python27\lib\site-packages\sympy\mpmath\matrices\linalg.py", line 406, in qr_solve
A, b = ctx.matrix(A, **kwargs).copy(), ctx.matrix(b, **kwargs).copy()
File "C:\Python27\lib\site-packages\sympy\mpmath\matrices\matrices.py", line 328, in __init__
A = self.ctx.matrix(args[0].tolist())
File "C:\Python27\lib\site-packages\sympy\mpmath\matrices\matrices.py", line 301, in __init__
self[i, j] = convert(a)
File "C:\Python27\lib\site-packages\sympy\mpmath\ctx_mp_python.py", line 662, in convert
return ctx._convert_fallback(x, strings)
File "C:\Python27\lib\site-packages\sympy\mpmath\ctx_mp.py", line 614, in _convert_fallback
raise TypeError("cannot create mpf from " + repr(x))
TypeError: cannot create mpf from -2.27448396079674e-13*I
这似乎发生在 sympy 在输入之前设置矩阵时,这对我来说似乎很奇怪,因为 I 表示 sympy 复杂类型.想我可能在某处使用了错误的矩阵或输入类型.
It seems to occur when sympy is setting up the matrices before input, which seems odd to me since the I indicate a sympy complex type. Thinking I'm perhaps using the wrong matrices or input type somewhere.
推荐答案
问题是 mpmath 不知道如何将 Sympy 对象 I
(虚数单位)转换成它的对象来表示复数.不过,它可以与 Python 的 j
一起使用,正如您所看到的 在源代码中.
The problem is that mpmath does not know how to convert Sympy object I
(imaginary unit) into its object for representing complex numbers. It can work with Python's j
, though, as you can see in the source.
需要注意的是,mpmath 是一个用于高精度浮点计算的库,它独立于 Sympy,它是一个符号计算库.不需要定义 Sympy 对象然后让 mpmath 使用它们.直接用mpmath就行了.
It should be noted that mpmath, a library for high-precision floating point computations, is independent of Sympy, a library for symbolic computations. There is no need to define Sympy objects and then ask mpmath to work with them. Just use mpmath directly.
import mpmath
mpmath.mp.dps = 50 # 50 digit arithmetic, for demonstration
A = mpmath.matrix([[2+3j, 1], [1, 1]])
b = mpmath.matrix([[1], [1]])
mpmath.qr_solve(A, b)
输出:
(matrix(
[[mpc(real='3.436455137311543569947658013827436034380299778494123e-55', imag='-1.2867118438861911327915233933248665673255859691704302e-55')],
[mpc(real='1.0', imag='-1.1953121943036561823547019562093175737721941131313411e-54')]]), mpf('1.7055229691470039210052256620915903242996742650953353e-54'))
这篇关于调用 qr_solve 时无法从复数创建 mpf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!