Similarly, for the other two values 2 and 15, 1 and 10 will be printed respectively. So, the corresponding value for ‘x<0’ in funclist, which is 0, will be printed. The condlist will output the value True for the first condition ‘x < 0’ and False for the rest two conditions.Īs mentioned above, we will print only those values from the funclist for which the corresponding value in the condlist is True. The function piecewise compares each value: -10, 2, and 15 with the interval condition.įirst, for the value -10, it will check the condlist. First, we shall import the numpy library. Let us understand the practical implementation of NumPy’s piecewise function in python. Out: The output is an n-dimensional array that has the same size as the parameter ‘x.’ Depending on the boolean value of the condlist, it calls the function in funclist.
Kw: A kw parameter is an optional dictionary that is passed to the function upon execution. It takes a one-dimensional array as an input and outputs a one-dimensional array or a scalar value.Īrgs: The args parameter is an optional tuple that is passed to the function upon execution. If the length of ‘funclist’ is one more than the length of ‘condlist’, then that will be the default value when the condition is False.įunclist: It is a list of callables. The function will consider only those values from ‘funclist’ for which the corresponding value in ‘condlist’ is True. The ‘condlist’ size should be the same as the size of the parameter ‘funclist’. The syntax of the piecewise function in the numpy library is: numpy.piecewise(x, condlist, funclist, *args, **kw) Parameters :Ĭondlist: It is a list of boolean arrays.
Instead of defining a complete function, we can reduce the entire function code to a single line using NumPy’s piecewise function. If we were to define the piecewise function for the above example using a user defined function, then the python code used would be: If input value is 5, then the function value would be ( 10 – 5 ), which is 5.įor input value 11, the function value would be ( 2*(11) + 3 ), which is 25. If the input value is -10, then the function value would be (10)^2, which is 100. So, for example, if the value of x lies between 0 and 10 where 10 is exclusive, then the sub-function ( 10 – x ) would be applied to it.Īnd if the value of x would be greater than or equal to 10, then the sub-function ( 2x + 3 ) would be applied to it. If x is negative, then the sub-function x^2 would be applied to it.
It has been defined over three intervals – Here, we have defined a piecewise function ‘f(x)’ in the above image. Let us understand with the help of an example. Depending on the interval in which the input value lies, a sub-function is defined for it. It is a function which has different sub functions.įor each interval, a sub-function is defined. Piecewise functions are those functions in mathematics which behave differently with different input values. Using numpy piecewise for multi dimensional array.