【发布时间】:2019-10-18 13:01:52
【问题描述】:
我想以最有效的方式计算蒸汽属性,考虑标量、向量和矩阵作为两个参数的输入选项。我担心的是,我必须使用 if 块相对于输入(标量、向量或矩阵)的大小,使代码变得很长。我是一个简单的机械工程师,对 python 很陌生,任何关于如何优化代码的帮助都非常感谢。这是代码:
from iapws.iapws97 import _Region4
import numpy as np
def h_x(P,x):
''' spec enthalpy in liquid, steam and wet (two-phase flow) regions
P - pressure in bar
x - drayness steam fraction [-]
h - specific heat of wet region returned [kJ/kW]
'''
mm = len(np.shape(x))
if mm == 0:
h_ = _Region4(P/10,0)['h']
h__ = _Region4(P/10,1)['h']
# return h_ + x * (h__ - h_)
return h_ + x * (h__ - h_)
elif mm == 1:
return np.array([ _Region4(i/10,0)['h'] + j * ( _Region4(i/10,1)['h'] - _Region4(i/10,0)['h'] ) for i,j in zip(P,x) ])
elif mm == 2:
mmm,nnn = x.shape
h = np.ndarray(shape=(mmm,nnn)) #(mm,nn)
for i in range(mmm):
for j in range(nnn):
h_ = _Region4(P[i,j]/10,0)['h']
h__ = _Region4(P[i,j]/10,1)['h']
h[i,j] = h_ + x[i,j] * (h__ - h_)
return h
else:
print('h_x input must be scalar, vector or 2D matrix!')
# code testing
P = np.array([[.0234,.0193,0.244],[.0244,.0185,0.254]])
x = np.array([[.812,.782,.620],[.912,.882,.820]])
h_x(P,x)
【问题讨论】:
-
我不知道效率,但代码方面...我会将所有内容转换为 2D 矩阵...因此计算代码将是一个块。
scalar -> [[ scalar ]], [ scalar1, scalar1 ] - > [[[ scalar1, scalar1 ]]
标签: python python-3.x performance optimization