我想找到给定 y 的 x 值(我想知道 t、X 转换达到 0.9 时)。到处都有这样的问题,他们说使用 np.interp 但我用两种方式做到了,但两种方式都是错误的。代码是:
import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
# Create time domain
t = np.linspace(0,4000,100)
# Parameters
A = 1.5*10**(-3) # Arrhenius constant
T = 300 # Temperature [K]
R = 8.31 # Ideal gas constant [J/molK]
E_a= 1000 # Activation energy [J/mol]
V = 5 # Reactor volume [m3]
# Initial condition
C_A0 = 0.1 # Initial concentration [mol/m3]
def dNdt(C_A,t):
r_A = (-k*C_A)/V
dNdt = r_A*V
return dNdt
k=A*np.exp(-E_a/(R*T))
C_A = odeint(dNdt,C_A0,t)
N_A0 = C_A0*V
N_A = C_A*V
X = (N_A0 - N_A)/N_A0
# Plot
plt.figure()
plt.plot(t,X,'b-',label='Conversion')
plt.plot(t,C_A,'r--',label='Concentration')
plt.legend(loc='best')
plt.grid(True)
plt.xlabel('Time [s]')
plt.ylabel('Conversion')
从图表中可以看出,大约在 t=2300 时,转换率为 0.9。
方法一:
我编写了这个函数,这样我就可以询问任何给定点并获取 x 值:
def find(x_val,f):
f = np.reshape(f,len(f))
global t
t = np.reshape(t,len(t))
return np.interp(x_val,t,f)
print('Conversion of 0.9 is reached at: ',int(find(0.9,X)),'s')
当我在 0.9 处调用该函数时,我得到 0.0008858
,它四舍五入为 0,这是错误的。我想当我声明 global t
时可能出了问题??
方法2:
当我在函数之外执行此操作时;所以我手动 reshape X和t并使用np.interp(0.9,t,X),输出是0.9。
X = np.reshape(X,len(X))
t = np.reshape(t,len(t))
print(np.interp(0.9,t,X))
我以为我在变量的顺序上犯了一个错误,所以我做了np.interp(0.9,X,t)
,结果再次让我惊讶的是 0.9。
我不确定我哪里出错了。任何帮助,将不胜感激。非常感谢:)
最佳答案
在你的绘图上,t 是水平的,X 是垂直的。您想要找到垂直坐标为 0.9 的水平坐标。也就是说,针对给定的 X 找到 t。 说
find x value for a given y
必然会导致困惑,正如这里所做的那样。
问题已解决
print(np.interp(0.9, X.ravel(), t)) # prints 2292.765497278863
(最好使用 ravel
进行展平,而不是像您那样进行 reshape )。不需要重新塑造t
,它已经是一维的了。
I did
np.interp(0.9,X,t)
, and again it surprised me with 0.9.
这听起来不太可能,您可能打错了。这是正确的顺序。
关于python - 使用 np.interp 查找给定 y 的 x 值会给出错误的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51804599/