Alternative Piecewise Functions

From www.norsemathology.org

Jump to: navigation, search

Contents

Alternative Piecewise Function

One serious shortcoming in Sage is its inability to define infinite ranges for piecewise functions. This page will show the progress of an alternative piecewise class, that I will hopefully at some point integrate with the current Piecewise implementation in Sage.

Code

class SimplePiecewise:
    def __init__(self, fr_list):
        self.__length = len( fr_list )
        self.__ranges = [ x[0] for x in fr_list ]
        self.__functions = [ x[1] for x in fr_list ]

    def __choose_function( self, val ):
        for i in range(0,self.__length):
            if self.__ranges[i][0] <= val <= self.__ranges[i][1]:
                return self.__functions[i]
        return None

    def __call__( self, arg1 ):
        f = self.__choose_function( arg1 )
        if f != None:
            return f( arg1 )
        else:
            raise ValueError('Error: ' + str(arg1) + ' is out of range.')

Usage

The usage of the SimplePiecewise class is identical to the standard Piecewise class in Sage, except now it is possible to specify infinite ranges.

Example

f = lambda x : x + 1
g = lambda x : x
pFunction = SimplePiecewise( [ [ (-infinity, 0), f], [ (1, infinity), g ] ] )
pFunction(-100)
#output -99
pFunction(10)
#output 10
Personal tools