1

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?

tjsmert44
  • 121
  • 1
  • 12
  • An `if` only works with single True/False values; it is not an 'iterator', so doesn't work with the `tempspace` array. One way or other need to call the two calculations with different ranges, for example `linspace(200,1872,1000)` and `linspace(1873,10000,500)`. `piecewise` can do the split for you, but it would be a good exercise to do the split yourself. – hpaulj Mar 27 '23 at 15:54

1 Answers1

1

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)
Beatdown
  • 187
  • 2
  • 7
  • 20