Features & Development

Problems with contextPiecewiseFunction.pl

Re: Problems with contextPiecewiseFunction.pl

by Davide Cervone -
Number of replies: 0
In order to use MathObject Formulas with the graphics routines, you need to use lower-level graphics calls rather than add_functions() and the other top-level plotting commands. This is because those routines use the old algebra parser rather than the MathObject parser to evaluate the mathematical formula to plot, and it doesn't know anything about things like "if" and "else".

But it's not that hard to do. Rather than

   $f_graph = FEQ("$f for x in [$xmin,$xmax] using color:red and weight:3");
   add_functions( $graph,$f_graph);
use
   $f_graph = new Fun($f->perlFunction,$graph);
   $f_graph->steps(10); $f_graph->color("red"); $f_graph->weight(3);
Here steps is chosen so that the corners of your function will be guaranteed to be plotted (otherwise you can get rounded-off corners). Since the function is linear in between the points, you can let the plotting routine do the interpolation between the grid lines. This speeds up the plotting.

Note, however, that your piecewise function will not be defined on the complete range that you have specified of -5 to 5 (since $fxnum[4] can be at most 4). That means you will get an error when trying to plot values higher than that. So you should probably make sure your function is defined over a wider range. Say

    $f = PiecewiseFunction(
      "[-6,$fxnum[0])" => $fynum[0],
      "[$fxnum[0],$fxnum[1])" => $f_parts[0],
      "[$fxnum[1],$fxnum[2])" => $f_parts[1],
      "[$fxnum[2],$fxnum[3])" => $f_parts[2],
      "[$fxnum[3],$fxnum[4])" => $f_parts[3],
      "[$fxnum[4],6]" => $fynum[4],
    );
which has the function being constant below $fxnum[0] and above $fxnum[4].

That should do it for you.

Davide