使用 matplotlib 时我遇到了一个很奇怪的问题。我有一个循环遍历模型的不同情况,对于每种情况,我希望它以图形形式输出求解的微分方程,然后询问用户是否想继续绘制图形。这是我目前正在使用的代码(为简单起见,只有一个案例):
import math
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
P1 = 100
P2 = 20
Pa = 14.6959
L = 11.811
D = 7/16
Ac= math.pi/4*D**2
Ar = .0305
ML = 2.2
MP = .31
v = .1
C = .95
k = 1
#Defines the Function to Solve the ODE
def dU_dx(U, x):
return [U[1],(P1*Ac-P2*Ac-Pa*Ar-(1-C)*v*U[1]-k*U[0])/(ML+MP)]
i =0
U0 = [0, 0]
t = np.linspace(0, 10, 200)
case = input("What state is the loop in (1-4)?")
case = int(case)
#The While Loop to Iterate through states and output the graph of the ODE
while i < 2:
if case == 1:
P1 = 100
P2 = 20
dU_dx
Usol = odeint(dU_dx, U0, t)
xsol = Usol[:,0]
plt.plot(t,xsol);
plt.show(block=False)
answer = input("Continue to plot? (y/n) ")
if answer == "y":
case = int(input("Enter the new case number : "))
elif answer == "n":
i = 2
else:
print("Please enter y or n.")
if case == 2:
P1 = 100
P2 = 0
dU_dx
Usol = odeint(dU_dx, U0, t)
xsol = Usol[:,0]
plt.plot(t,xsol);
plt.show(block=False)
answer = input("Continue to plot? (y/n) ")
#The code for states 3 and 4 are identical to the code for states 1 and 2, with different values for P1 and P2. I haven't written them yet, and including them would only make the could longer with no additional insights.
else:
print ("Inproper state!")
case = int(input("Specify a new case number : "))
plot 函数的两个输入在循环外的函数中定义,并在循环外按预期工作。但是,当代码运行时,代码会跳过图形,然后不会提示用户输入并继续运行。我已经设法通过添加plt.show(block=True)below来显示图plt.plot,但是在这样做之后,代码仍然会在显示图形后停止并且不允许代码继续。
此循环的最终目标是绘制 ODE 的解,然后询问用户是否愿意绘制另一个具有略微不同常数的相同形式的 ODE。我怎样才能让 Python 允许我在这个循环中绘制我的函数并允许切换案例?
慕尼黑8549860
相关分类