如何在python上求解三角方程

时间:2018-08-09 15:26:31

标签: python math sympy equation-solving

我正在尝试用python解决3个三角方程。我使用了Sympy库,但出现了诸如“ TypeError:无法将表达式转换为浮点数”之类的错误

这是我的Python源代码:

from sympy import Symbol, solve, Eq
from math import*

# Robot Arm length
L1 = 0
L2 = 97.9
L3 = 120
L4 = 120
L5 = 184

# location
x = L1+L2+L3+L4+L5
y = 0
z = 0

x1 = Symbol('x1',real = True)
x2 = Symbol('x2',real = True)
x3 = Symbol('x3',real = True)

#trigonometric equations

e1= Eq(L1 - (5*sin(x1))/2 - L4*(cos(x1)*sin(x2)*sin(x3) - cos(x1)*cos(x2)*cos(x3)) - L5*(cos(x4)*(cos(x1)*sin(x2)*sin(x3) - cos(x1)*cos(x2)*cos(x3)) + sin(x4)*(cos(x1)*cos(x2)*sin(x3) + cos(x1)*cos(x3)*sin(x2))) + L2*cos(x1) + L3*cos(x1)*cos(x2) - x)
e2= Eq((5*cos(x1))/2 + L4*(cos(x2)*cos(x3)*sin(x1) - sin(x1)*sin(x2)*sin(x3)) + L5*(cos(x4)*(cos(x2)*cos(x3)*sin(x1) - sin(x1)*sin(x2)*sin(x3)) - sin(x4)*(cos(x2)*sin(x1)*sin(x3) + cos(x3)*sin(x1)*sin(x2))) + L2*sin(x1) + L3*cos(x2)*sin(x1) - y)
e3= Eq(-L4*(cos(x2)*sin(x3) + cos(x3)*sin(x2)) - L3*sin(x2) - L5*(cos(x4)*(cos(x2)*sin(x3) + cos(x3)*sin(x2)) + sin(x4)*(cos(x2)*cos(x3) - sin(x2)*sin(x3))) - z)

solve([e,e2,e3],x1,x2,x3)

x1 = degrees(x1)
x2 = degrees(x2)
x3 = degrees(x3)

print("degree values : ",x1,x2,x3)

我添加了我的错误消息:

enter image description here

谁能告诉我应该更改代码的哪一部分?

2 个答案:

答案 0 :(得分:3)

from math import *是主要错误。函数math.sinmath.cos仅用于数字计算,不能给它们提供符号参数。必须从SymPy导入任何数学函数,才能在符号计算中使用它们。

指南:使用SymPy时,请勿从math导入任何内容。将导入更改为

from sympy import *

将解决大多数问题。您仍然必须定义当前未定义的x4

答案 1 :(得分:0)

我无法不告诉您完整的代码,但是看起来e3行上的变量“ x4”尚未在任何地方声明。