Update 2: Got two solid answers, but had trouble implementing one, and found the other could only save me computation time by sacrificing accuracy. So I chose neither as an official answer, but they're both worth looking at if you're trying to interpolate a "sharp" (not smooth) function.
Update: The main question has been answered, but my problem hasn't been solved. The problem is I have a situation where I want to use Which on an InterpolatingFunction several times to repeatedly "fold" the function. But I'm finding that as soon as I nest Which even once (i.e. use a Which'd function for both values of a new Which call), I get a slow down when using the resulting function of >300%. I can find no other explanation for the slowing down. So I'm attempting to turn the first Which into an InterpolatingFunction to simplify the final function. Any suggestions on a better solution?
I define these two functions:
x1 = FunctionInterpolation[Sin[t], {t, 0, 20}];
x2 = FunctionInterpolation[
Which[x1[t] >= 0, x1[t], x1[t] < 0, -x1[t]], {t, 0, 20}];
and find that the latter gives a bizarre, incorrect function:
Plot[x1[t], {t, 0, 20}]
Plot[x2[t], {t, 0, 20}, PlotRange -> {-1.1, 1.1}]
The problem is that the second graph should look like the absolute value of the first. I'm trying to understand why the combination of FunctionInterpolation -> Which -> FunctionInterpolation has this effect so I can fix it.
My actual code is more complex than this (this is just a reduced sample case), so workarounds specific to this case wouldn't be very helpful. Anyone know what's going on?
y==0
.Abs[Sin[t]]
does better. $\endgroup$Which
outside theInterpolatingFunction
? That is, interpolate the smooth function first (which will work nicely), then take the absolute value (or whatever it is you need to do) afterward. $\endgroup$PiecewiseExpand
on theWhich
statements to see if you can avoid interpolating. $\endgroup$