Cannot create mpf from a complex number when calling qr_solve

萝らか妹 提交于 2019-12-10 22:58:28

问题


I make the following imports:

from sympy.matrices import Matrix as sy_matrix
import sympy.mpmath as sy_mp

Create my matrices like this:

sysMat = sy_matrix([[0.0]*sz1]*sz2)       
resVec = sy_matrix([[0.0]]*sz2)

.Populate then with python complex numbers (eg 1.0+1.0j) and then call:

coeffVec = sy_mp.qr_solve(sysMat, resVec)

However I get the following exception:

  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

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.


回答1:


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.

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)

Output:

(matrix(
[[mpc(real='3.436455137311543569947658013827436034380299778494123e-55', imag='-1.2867118438861911327915233933248665673255859691704302e-55')],
 [mpc(real='1.0', imag='-1.1953121943036561823547019562093175737721941131313411e-54')]]), mpf('1.7055229691470039210052256620915903242996742650953353e-54'))


来源:https://stackoverflow.com/questions/36810785/cannot-create-mpf-from-a-complex-number-when-calling-qr-solve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!