如何使用 Sympy 分离方程的实部和虚部?

How can I separate real and imaginary parts of an equation using Sympy?

我目前正在编写 Python 脚本来执行四杆 linkage 的运动学分析。

四小节 linkage 可以在数学上表示为向量循环方程:

a\*e^(j\*theta1) + b\*e^(j\*theta2) + c\*e^(j\*theta3) + d\*e^(j\*theta4) = 0

其中:

这里,abcdtheta4的值是已知的,而theta1行为作为输入变量。因此,theta2theta3theta1.

的函数

对于脚本的第一部分,我希望 sympy 执行以下操作:

我目前的代码如下:

from sympy import *

a, b, c, d, theta1, theta4 = symbols("a b c d theta1 theta4", real=True)
theta2 = Function("theta2")(theta1)
theta3 = Function("theta3")(theta1)

vector_loop = a*exp(I*theta1) + b*exp(I*theta2) + c*exp(I*theta3) + d*exp(I*theta4)
vector_loop_trig = vector_loop.rewrite(cos).expand()
vector_loop_real = re(vector_loop_trig)
vector_loop_im = im(vector_loop_trig)

我从代码中得到的输出是:

实部:

a⋅cos(θ₁) - b⋅cos(re(θ₂(θ₁)))⋅sinh(im(θ₂(θ₁))) + b⋅cos(re(θ₂(θ₁)))⋅cosh(im(θ₂(θ₁))) - c⋅cos(re(θ₃(θ₁)))⋅sinh(im(θ₃(θ₁))) + c⋅cos(re(θ₃(θ₁)))⋅cosh(im(θ₃(θ₁))) + d⋅cos(θ₄)

虚部:

a⋅sin(θ₁) - b⋅sin(re(θ₂(θ₁)))⋅sinh(im(θ₂(θ₁))) + b⋅sin(re(θ₂(θ₁)))⋅cosh(im(θ₂(θ₁))) - c⋅sin(re(θ₃(θ₁)))⋅sinh(im(θ₃(θ₁))) + c⋅sin(re(θ₃(θ₁)))⋅cosh(im(θ₃(θ₁))) + d⋅sin(θ₄)

但是,我应该得到的输出是:

实部:

a⋅cos(θ₁) + b⋅cos(θ₂) + c⋅cos(θ₃) + d⋅cos(θ₄)

虚部:

a⋅sin(θ₁) + b⋅sin(θ₂) + c⋅sin(θ₃) + d⋅sin(θ₄)

如何修正我的代码以获得正确的输出?

您需要将 theta2 和 theta3 声明为真实的:

theta2 = Function("theta2", real=True)(theta1)
theta3 = Function("theta3", real=True)(theta1)