5
$\begingroup$

I would like to create the following function: It should approximate a function func[x] by piecewise polynomial interpolations, splitting the approximate function in n different polynomials, from xMin to xMax.

autoPiecewiseApproximation[func[x],{xMin,xMax,n}]

Example: the square root function

For instance for two subdivisons n = 2 and xMin = 0, xMax = 1, the function would automatically generate this:

m = Piecewise[{{Fit[
     Table[{x, Sqrt[x]}, {x, 0, 0.5, .01}], {1, x, x^2, E^x}, x] , 
    0 <= x <= 0.5}, {Fit[
     Table[{x, Sqrt[x]}, {x, 0.5, 1, .01}], {1, x, x^2, E^x}, x] , 
    0.5 < x <= 1}}]

Anyone knows how to do this correctly ?

$\endgroup$
5
$\begingroup$
pW[f_, n_, m_, min_: 0, max_: 1] := Piecewise[
  {Fit[Table[{x, f @ x}, {x, ##, (#2 - #)/m}], {1, x, x^2, E^x}, x], # < x <= #2} & @@@
   Partition[Subdivide[min, max, n], 2, 1]] 

Examples:

pW[Sqrt, 4, 10] // TeXForm

$\small\begin{cases} -149.176 x^2-246.803 x+251.787 e^x-251.768 & 0<x\leq \frac{1}{4} \\ -2.882 x^2-1.65139 x+3.18162 e^x-2.99226 & \frac{1}{4}<x\leq \frac{1}{2} \\ -0.876557 x^2+0.489058 x+0.663232 e^x-0.41176 & \frac{1}{2}<x\leq \frac{3}{4} \\ -0.418328 x^2+0.738036 x+0.220335 e^x+0.0813601 & \frac{3}{4}<x\leq 1 \end{cases}$

pW[Sqrt, 5, 50, 5, 15] // TeXForm

$\small\begin{cases} -0.010714 x^2+0.328728 x+\text{9.866783884779016$\grave{ }$*${}^{\wedge}$-6} e^x+0.858866 & 5<x\leq 7 \\ -0.00658734 x^2+0.280252 x+\text{6.475622629784991$\grave{ }$*${}^{\wedge}$-7} e^x+1.00608 & 7<x\leq 9 \\ -0.00455749 x^2+0.248165 x+\text{5.00746734942773$\grave{ }$*${}^{\wedge}$-8} e^x+1.13528 & 9<x\leq 11 \\ -0.00338884 x^2+0.224974 x+\text{4.292376170350944$\grave{ }$*${}^{\wedge}$-9} e^x+1.25171 & 11<x\leq 13 \\ -0.00264528 x^2+0.207225 x+\text{3.949544062291019$\grave{ }$*${}^{\wedge}$-10} e^x+1.3585 & 13<x\leq 15 \end{cases}$

$\endgroup$
  • $\begingroup$ This is great ! Thanks a lot ! Can you just explain me what n and m is used for ? Is there any way to also include the function (like Sqrt) as an input to pW[] ? $\endgroup$ – james Sep 4 '18 at 8:21
  • $\begingroup$ @james, n is the number of pieces the domain $[min,max]$ is divided into. m is the number of points used for Fitting for each piece. You can make the function to approximated an argument using pW[f_,n_,m_,min_:0,max_:1] := ... and replacing Sqrt with f on the right-hand-side of the definition. $\endgroup$ – kglr Sep 4 '18 at 8:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.