pythonsage

Integrate and plot a piecewise function in Sagemath


I'm trying to integrate a piecewise function using Sagemath, and finding it to be impossible. My original code is below, but it's wrong due to accidental evaluation described here.

def f(x):
    if(x < 0):
        return 3 * x + 3
    else:
        return -3 * x + 3

g(x) = integrate(f(t), t, 0, x)

The fix for plotting mentioned on the website is to use f instead of f(t), but this is apparently unsupported for the integrate() function since a TypeError is raised.

Is there a fix for this that I'm unaware of?


Solution

  • Instead of defining a piecewise function via def, use the built-in piecewise class:

    f = Piecewise([[(-infinity, 0), 3*x+3],[(0, infinity), -3*x+3]]) 
    f.integral()
    

    Output:

    Piecewise defined function with 2 parts, [[(-Infinity, 0), x |--> 3/2*x^2 + 3*x], [(0, +Infinity), x |--> -3/2*x^2 + 3*x]]
    

    The piecewise functions have their own methods, such as .plot(). Plotting does not support infinite intervals, though. A plot can be obtained with finite intervals

    f = Piecewise([[(-5, 0), 3*x+3],[(0, 5), -3*x+3]]) 
    g = f.integral()
    g.plot()
    

    But you also want to subtract g(0) from g. This is not as straightforward as g-g(0), but not too bad, either: get the list of pieces with g.list(), subtract g(0) from each function, then recombine.

    g0 = Piecewise([(piece[0], piece[1] - g(0)) for piece in g.list()])
    g0.plot()
    

    And there you have it:

    plot

    By extending this approach, we don't even need to put finite intervals in f from the beginning. The following plots g - g(0) on a given interval [a,b], by modifying the domain:

    a = -2
    b = 3
    g0 = Piecewise([((max(piece[0][0], a), min(piece[0][1], b)), piece[1] - g(0)) for piece in g.list()])
    g.plot()
    

    plotrange