首先,我可以绘制一些我声明为函数的东西吗?因为我遇到了很多错误,但没有显示错误在哪里,例如:
import sympy as sy
rho = 1000 # Density of water [kg/m3]
A = 1.0 # Cross-sectional area of tank [m2]
c = 50 # Valve constant [kg/s per opening percent]
o = 100 # Percent valve opening
h = sy.Function('h')
t = sy.symbols('t')
m_bal = sy.Eq(h(t).diff(t),c/(rho*A)*o)
gen_sol = sy.dsolve(m_bal,h(t))
C = gen_sol.subs([(t,0),(h(0),0)])
sol = gen_sol.subs([(C.rhs,C.lhs)])
sy.plot(t,h)
然后我得到:
---------------------------------------------------------------------------
AssertionError Traceback (most recent call last)
<ipython-input-54-7aa8880d452a> in <module>()
14 C = gen_sol.subs([(t,0),(h(0),0)])
15 sol = gen_sol.subs([(C.rhs,C.lhs)])
---> 16 sy.plot(t,h)
~\Anaconda3\lib\site-packages\sympy\plotting\plot.py in plot(*args, **kwargs)
1288 show = kwargs.pop('show', True)
1289 series = []
-> 1290 plot_expr = check_arguments(args, 1, 1)
1291 series = [LineOver1DRangeSeries(*arg, **kwargs) for arg in plot_expr]
1292
~\Anaconda3\lib\site-packages\sympy\plotting\plot.py in check_arguments(args, expr_len, nb_of_free_symbols)
1791
1792 exprs = args[:i]
-> 1793 assert all(isinstance(e, Expr) for expr in exprs for e in expr)
1794 free_symbols = list(set().union(*[e.free_symbols for expr in exprs
1795 for e in expr]))
AssertionError:
其次,我想将t = 0
到t = 10
的内容绘制成图,而我只想为o = 100
绘制t = [2,7]
。我已经做到了,但是我不知道我要去哪里错了:
import sympy as sy
sy.init_printing()
rho = 1000 # Density of water [kg/m3]
A = 1.0 # Cross-sectional area of tank [m2]
c = 50 # Valve constant [kg/s per opening percent]
o = 100
h = sy.Function('h')
t = sy.symbols('t')
m_bal = sy.Eq(h(t).diff(t),c/(rho*A)*o)
gen_sol = sy.dsolve(m_bal,h(t))
C = gen_sol.subs([(t,0),(h(0),0)])
sol = gen_sol.subs([(C.rhs,C.lhs)])
sy.plot(t,h)
我可以在sympy上执行此操作,还是必须使用matplotlib和numpy并执行以下操作:
o= np.zeros(100) # % Valve opening
o[21:70] = 100 # % opening at times 2s to 7s
答案 0 :(得分:1)
sy.plot(t, h)
由于多种原因而存在问题。首先,在SymPy的plot
中,函数位于变量之前:例如sy.plot(t**2, (t, 0, 3))
。
第二,您对ODE所做的任何操作都不会对t
或h
产生任何影响。您只是在尝试使用sy.Function('h')
进行绘制,而没有指示h
是什么。 SymPy对象不会发生突变。除非您为h
分配内容,否则它不会改变。
强制执行初始条件的尝试也很奇怪。在当前版本的SymPy(1.2)中,初始条件可由dsolve
本身施加。这就是我要解决和绘制解决方案的方式:
sol = sy.dsolve(m_bal, h(t), ics={h(0): 0})
sy.plot(sol.rhs, (t, 0, 3))