I am currently trying to plot a piecewise function that looks like the following:
def kappa_function(x):
if (x < 1873):
return 120.5 - 0.1488*(x - 273.15)+ (1.554e-4)*(x-273.15)**2 - 9.153e-8*(x - 273.15)**3 + 2.093e-11*(x - 273.15)**4
elif x >=1873:
return 42-(x-1873)/70 + ((x-1873)**2)/500000
tempspace = np.linspace(200,10000,10000)
kappa_f = kappa_function(tempspace)
However, when I run this, I get the following:
Traceback (most recent call last):
File "C:\Users\smith\Documents\Fenics\carbon-constants.py", line 20, in <module>
kappa_f = kappa_function(tempspace)
File "C:\Users\smith\Documents\Fenics\carbon-constants.py", line 14, in kappa_function
if (x < 1873):
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
How do I resolve this problem?
Thanks in advance
EDIT: Further to the proposed answer, if we extend this system to 3 conditions in condlist
, the error returns:
def kappa_function(x):
condlist = [x < 1873, 1873 < x < 2000, x > 2000]
funclist = [lambda x: 120.5 - 0.1488*(x - 273.15)+ (1.554e-4)*(x-273.15)**2 - 9.153e-8*(x - 273.15)**3 + 2.093e-11*(x - 273.15)**4,
lambda x: 42-(x-1873)/70 + ((x-1873)**2)/500000, 1]
return np.piecewise(x, condlist, funclist)
How can this be resolved?
You can use np.piecewise() for this task to create a piecewise function like this..
import numpy as np
def kappa_function(x):
condlist = [x < 1873, x >= 1873]
funclist = [lambda x: 120.5 - 0.1488*(x - 273.15)+ (1.554e-4)*(x-273.15)**2 - 9.153e-8*(x - 273.15)**3 + 2.093e-11*(x - 273.15)**4,
lambda x: 42-(x-1873)/70 + ((x-1873)**2)/500000]
return np.piecewise(x, condlist, funclist)
tempspace = np.linspace(200, 10000, 10000)
kappa_f = kappa_function(tempspace)