Search code examples
matrixtypeerrorsympysolver

sympy nsolve typeError with Matrix starting vector


I'm getting a TypeError with nsolve when I give it a Matrix for the starting vector. Notably, nsolve is perfectly fine with the fact that the equation is a Matrix expression. Here's a basic example:

import sympy as sy
v = sy.Matrix(sy.symarray("v", (2,)))
w = sy.Matrix([17, 23])
equation = v - w

The following line gives a TypeError: cannot create mpf from Matrix([[17],[23]]):

sy.nsolve(equation, v, w)

The following line is a kludgy workaround which gives the correct output, Matrix([[17.0],[23.0]]):

sy.nsolve(equation, v, w.T.tolist()[0])

Is there a better solution than this workaround?


Solution

  • The workaround you have is necessary, given the following:

    1. nsolve passes the x0 argument directly to mpmath.findroot, on this line
    2. findroot only supports iterables in x0 that satisfy isinstance(x0, (list, tuple)), on this line. Moreover it has to be a flat tuple or list; its elements are assumed to be scalars in the subsequent x0 = [ctx.convert(x) for x in x0].

    A SymPy matrix is not an instance of either list or tuple. Also, w.tolist() is not enough because the resulting list is nested. Hence the need for w.T.tolist()[0].


    This is now an open issue in SymPy repo.