Search code examples
maxima

Solving piecewise functions in Maxima


I attempted to solve a piecewise function in Maxima, but none of the solutions of the functions were returned:

piecewiseExample(x) := if (x < 5) then x*2 else x/2;

solve([piecewiseExample(x) = 4], [x]);
//result: [(if x<5 then 2*x else x/2)=4]

Is it possible for Maxima to obtain the solutions of an equation like this one?


Solution

  • In simple cases you can solve every branch everywhere and filter solutions:

    solve_and_filter(eq, var, p):= block([so: solve(eq, var), prederror: true],
      sublist(so, lambda([c], p(rhs(c))))) $
    
    pw_solve(pw, var):= map(lambda([L],
        solve_and_filter(first(L), var, second(L))), pw) $
    
    /* represent piecewise equation as a list of equation-predicate pairs
       [ [eq1, pred1], [eq2, pred2], ... ] */
    pw: [ [x*2 = 4, lambda([x], x< 5)],
          [x/2 = 4, lambda([x], x>=5)]] $
    
    /* solve every `eq' and filter solutions using `pred' */
    pw_solve(pw, x);