Python – Construct a piecewise function using logic

Question:

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:UserssmithDocumentsFenicscarbon-constants.py", line 20, in <module>
    kappa_f = kappa_function(tempspace)
  File "C:UserssmithDocumentsFenicscarbon-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?

Asked By: tjsmert44

||

Answers:

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)
Answered By: Beatdown
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.