我正在使用sympy 1.6.1,并且我试图通过分析来解决sympy中的一个非常简单的问题。即从点(x,y)=(0,0)以初始速度$ v_x = 1,v_y = 1 $发射质量。这基本上可以归结为以下问题(我使用的是乳胶语法,很不幸,这里似乎不支持该语法):
d^2/dt^2 x(t)= 0
d^2/dt^2 y(t)= -g
,初始条件为:
x(0)=0
xprime(0)=1
y(0)=0
yprime(0)=1
我将这个问题重写为一组一阶方程,具有以下变量对应:
然后我尝试了以下代码:
import numpy as np
import sympy as sp
from scipy import integrate
import timeit
import matplotlib.pyplot as plt
# %% ===================================
def jcs_v1_not_working():
''' First attempt to solve problem which is not working
'''
g=-10
t, C1, C2= sp.symbols("t C1 C2")
x, y = sp.symbols("x y", cls = sp.Function, Function = True)
dx = x(t).diff(t)
dy = y(t).diff(t)
dx2 = x(t).diff(t,2)
dy2 = y(t).diff(t,2)
eq1 = sp.Eq( dx2, 0)
eq2 = sp.Eq( dy2-g, 0)
soln = sp.dsolve((eq1, eq2) ) #, ics = {x: 0, y: 0, dx:1, dy:1})
soln
jcs_v1_not_working()
输出为
UnboundLocalEror: Local variabl \gsol1' refrenced before assignment
这是一个小问题,我可以通过执行以下操作来绕过它。
def solve_2axis(tis):
"""solving one ode at a time
This version works for x-y
Args:
tis : time array
Returns:
dict: {'t','x','y'}
"""
t = sp.symbols('t')
x = sp.Function('x')
y = sp.Function('y')
g= -10
# calc X axis
dx = sp.Derivative(x(t),t)
dx2 = sp.Derivative(x(t),t,t)
resx = sp.dsolve(dx2 ,x(t),ics={x(t).subs(t,0): 0, dx.subs(t, 0): 1})
resxf = sp.lambdify(t,resx.rhs)
# Calc y axis
dy = sp.Derivative(y(t),t)
dy2 = sp.Derivative(y(t),t,t)
resy = sp.dsolve(dy2 - g ,y(t),ics={y(t).subs(t,0): 0, dy.subs(t, 0): 1})
resyf = sp.lambdify(t,resy.rhs)
# ploting data
plt.plot(tis, resxf(tis), '.', label= 'x')
plt.plot(tis, resyf(tis), '.', label= 'y')
plt.legend()
plt.xlabel('Time [s]')
plt.ylabel('x [m]')
return {'t': tis, 'x': resxf(tis), 'y': resyf(tis)}
solve_2axis(np.linspace(0.0.2,101)
尽管有解决方案,但我想知道在这种情况下我是否做错了什么,或者这是否是sympy dsolve中的错误。 Maxima和Matlab致力于解决这个问题。