我正在尝试写一个方程来执行以下操作:
1)积分方程
2)存储该公式供以后使用
3)在100个不同的间隔上对第一个方程进行数值积分并求出第二个方程,每次增加一个固定量
import math
from sympy import *
import kvalues
import time
import random
import pandas as pd
import matplotlib.pyplot as plt
第一个任务很简单,我是这样完成的:
def integration_gas(number,Fa_0,Fb_0,Fc_0,v_0,a,b,c,d,e):
Ca_0 = Fa_0/v_0
Cb_0 = Fb_0/v_0
Cc_0 = Fc_0/v_0
Ft_0 = Fb_0 + Fa_0 + Fc_0
theta1 = Cb_0/Ca_0
stoic1 = b/a
theta2 = Cc_0/Ca_0
stoic2 = c/a
stoic3 = d/a
stoic4 = e/a
Cd = stoic3*x
Ce = stoic4*x
sigma = e+d-c-b-1
epsilon = (Fa_0/Ft_0)*sigma
Ca_eq = Ca_0*((1-x)/(1+epsilon*x))
Cb_eq = Ca_0*((1*theta1-stoic1*x)/(1+epsilon*x))
Cc_eq = Ca_0*((1*theta2-stoic2*x)/(1+epsilon*x))
ra = 1*(Ca_eq**a)*(Cb_eq**b)*(Cc_eq**c)*final_k[number-1]
equation = Fa_0/ra
int1 = Integral(equation,x)
pprint(int1)
evaluate = int1.doit()
pprint(evaluate)
return equation
这部分代码可以很好地工作,直到第二部分。
def Ra_gas(number,Fa_0,Fb_0,Fc_0,v_0,a,b,c,d,e):
Ca_0 = Fa_0/v_0
Cb_0 = Fb_0/v_0
Cc_0 = Fc_0/v_0
Ft_0 = Fb_0 + Fa_0 + Fc_0
theta1 = Cb_0/Ca_0
stoic1 = b/a
theta2 = Cc_0/Ca_0
stoic2 = c/a
sigma = e+d-c-b-1
epsilon = (Fa_0/Ft_0)*sigma
Ca_eq = Ca_0*((1-x)/(1+epsilon*x))
Cb_eq = Ca_0*((1*theta1-stoic1*x)/(1+epsilon*x))
Cc_eq = Ca_0*((1*theta2-stoic2*x)/(1+epsilon*x))
ra = 1*(Ca_eq**a)*(Cb_eq**b)*(Cc_eq**c)*final_k[number-1]
pprint(ra)
return ra
这部分代码也可以正常工作。所以对于最后一部分,我有以下代码:
Number = 4
FA0 = 10
FB0 = 25
FC0 = 5
V0 = 2
A = 1
B = 2
C = 0.5
D = 1
E = 1
Ra = []
volume = []
Xff = []
eq1 = integration_gas(Number,FA0,FB0,FC0,V0,A,B,C,D,E)
Ra1 = Ra_gas(Number,FA0,FB0,FC0,V0,A,B,C,D,E)
#print(Ra1)
Xf = 0.01
# Calculates the reaction rate and volume for every interval of conversion
while Xf <=1:
int2 = Integral(eq1,(x,0,Xf))
volume.append(int2.doit())
f = lambdify(x,Ra1,"math")
f(Xf)
Ra.append(f(Xf))
Xff.append(Xf)
Xf += 0.01
然后我将结果绘制出来。我写的所有内容在某些情况下都可以正常工作,并且大约需要10到15秒即可完成。但是,特别是在这种情况下,我已经将这个代码运行了5个多小时,没有任何解决方案。如何优化此代码?
答案 0 :(得分:-1)
看看sympy,它可以符号积分原始方程式,然后可以通过numpy对其求值。对于“真实”数学Python有点慢,scipy Stack(numpy,matplotlib,sympy ...)要快得多。
虽然5个多小时有点长,但是您确定它确实可以执行吗?
编辑:一个简单的尝试 抱歉,刚才注意到您要羊羔化,您可能想包括您的进口货,以便人们看到您在使用什么。
开头:
import numpy as np
让我们看一下这段代码:
Xf = 0.01
while Xf <=1:
int2 = Integral(eq1,(x,0,Xf))
volume.append(int2.doit())
f = lambdify(x,Ra1,"math") #you're lambdifying each iteration that takes time
f(Xf) # no assignment here, unless you're doing something in place this line does nothing
Ra.append(f(Xf))
Xff.append(Xf)
Xf += 0.01
与此类似:
Xf = np.arange(0.01, 1.01, 0.01) #vector with values from 0.01 to 1 in steps of 0.01
f = np.vectorize(lambdify(x,Ra1,"math")) # you anonymous function but able to take np vectors/np arrays
Ra = f(Xf)
#Xff would be Xf