1 | initial version |
To turn a Python function (REFPROP 9.1) into a vectorized version, you can use the NumPy module. NumPy provides a way to work with arrays of data efficiently and can be used to vectorize scalar functions. The general steps to vectorize a function using NumPy are as follows:
vectorize()
function to create a vectorized version of the function.Here is an example of how to vectorize a function for calculating the vapor pressure of water at a given temperature using the REFPROP 9.1 library:
import numpy as np
from ctypes import c_double, byref, CDLL
# Load REFPROP 9.1 shared library
RPP = CDLL('REFPROP.dll')
# Define function to calculate vapor pressure of water at a given temperature
def water_sat_p(T):
T = c_double(T)
D = c_double(0.0)
P = c_double(0.0)
Q = c_double(0.0)
K = c_double(0.0)
err = c_double(0.0)
# Call REFPROP 9.1 function to calculate vapor pressure
RPP.SATPdll(byref(T), byref(D), byref(P), byref(Q), byref(K), byref(err), 255)
return P.value
# Vectorize the function using NumPy
water_sat_p = np.vectorize(water_sat_p)
# Define temperature array
T = np.linspace(273, 373, 101)
# Calculate vapor pressure at each temperature using vectorized function
P = water_sat_p(T)
# Print results
print('Temperature (K):', T)
print('Vapor pressure (Pa):', P)
In this example, the water_sat_p
function is first defined to calculate the vapor pressure of water at a given temperature using the REFPROP 9.1 library. Next, the function is vectorized using the np.vectorize()
function, which creates a new function that can be used with NumPy arrays. Finally, the vectorized function is used with a NumPy array of temperatures to calculate the vapor pressure at each temperature, and the results are printed to the console.