简体   繁体   中英

Sympy: TypeError: can't convert expression to float

I am trying to solve a simple system of equations in sympy but I'm getting the error: "TypeError: can't convert expression to float".

import sympy as sy
q0,q1,x,y = sy.symbols('q_0,q_1,x,y')
s = sy.Matrix([sy.Eq(x-sy.cos(q0)-sy.cos(q0+q1),0),
            sy.Eq(y-sy.sin(q0)-sy.sin(q0+q1),0)]);
sol = sy.solve(s.subs({x:2,y:0}),q0,q1)

The solution should be (0,0). I am using sympy version: 0.7.6-git.

Here is a partial solution:

import sympy as sy

q0, q1, x, y = sy.symbols('q_0,q_1,x,y', real=True, positive=True)
cq0, cq1, sq0, sq1 = sy.symbols('cq0, cq1, sq0, sq1', real=True)
s = sy.Matrix([sy.Eq(x - sy.cos(q0) - sy.cos(q0 + q1), 0),
               sy.Eq(y - sy.sin(q0) - sy.sin(q0 + q1), 0)])
# Matrix([
# [x - cos(q_0) - cos(q_0 + q_1) == 0],
# [y - sin(q_0) - sin(q_0 + q_1) == 0]])

s2 = sy.expand_trig(s).subs({
    sy.cos(q0) : cq0
    , sy.cos(q1) : cq1
    , sy.sin(q0) : sy.sqrt(1-cq0**2)
    , sy.sin(q1) : sy.sqrt(1-cq1**2)})

solns = set(sy.solve(s2.subs({x: 2, y: 0}), cq0, cq1))
for soln in solns:
    print(soln)

yields

(1, 1)

If you rewrite the matrix entries in terms of exp and don't check the answer, it works well:

>>> print(filldedent(
... solve(s.applyfunc(lambda x:x.rewrite(exp)).subs({x:2,y:0}), q0, q1, check=0)))

[(0, 0), (zoo, pi), (pi, 0), (-I*log(-sqrt(exp(zoo))), zoo),
(-I*log(sqrt(exp(zoo))), zoo)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM