Comparing $f(x)$ and the $f\_approx(x)$ in Matlab, Octave or Mathematica/Wolfram

68 Views Asked by At

I have a function $f(x)$ and I wrote the approximation for $f(x)$ as $f\_approx(x)$ which is a simple algebraic formula with sums and products .

I now want to study the 2 functions side by side and see :

  • how much they differ on average on a given range
  • if there is a coefficient that multiplied by $f\_approx(x)$ can improve the accuracy of $f\_approx(x)$ itself
  • if there is a constant difference so I can just add back the gap to $f\_approx(x)$

The main problem is that I haven't really found much in Matlab, Octave and Mathematica that really tackles my problem as I wish this softwares could do and plotting doesn't help much because the current versions of the functions only diverge for some zero-point-zero-something and it's a difference that I can't really appreciate graphically when my Domain is spanning over a couple of integers .

Thanks for your help.

As an example :

$f(x) = sin(x)$

$f\_approx(x) = x-(x^3/3!)$

1

There are 1 best solutions below

1
On BEST ANSWER

Suppose that the function is $f(x)$ and its approximation is $g(x)$ and suppose that you are concerned by a given range $a\leq x \leq b$.

You can define two error functions, for example $$r_1(x)=f(x)-g(x)$$ $$r_2(x)=\frac {f(x)-g(x)}{f(x)}$$ Plotting these functions over the given range would immediately show you the kind of errors (absolute and relative) related to the approximation.

If you want to improve the approximation multiplying $g(x)$ by a constant $A$, you can define $$I=\int_a^b \left(f(x)-Ag(x)\right)^2\,dx$$ and now, compute $\frac{dI}{dA}$ and ask for the solution of $$\frac{dI}{dA}=0$$

If you want to improve the approximation shifting $g(x)$ by a constant $A$, you can define $$I=\int_a^b \left(f(x)-g(x)+A\right)^2\,dx$$ and now, compute $\frac{dI}{dA}$ and ask for the solution of $$\frac{dI}{dA}=0$$ All of this work is doable formally using a CAS.

Let me try with your example using $(a=0,b=1)$. What I should write (hoping thet I properly remember Mathematica syntax) is

f[x_]:=Sin[x]

g[x_]:=x-x^3/6

Int=Integrate[(f[x]-A g[x])^2,{x,0,1}]

Der=D[Int,A]

Solve[Der==0,A]

This should give you $$\text{Int}=\frac{341 A^2}{1260}-3 A \sin (1)+\frac{11}{3} A \cos (1)+\frac{1}{2}-\frac{\sin (2)}{4}$$ $$\text{Der}=\frac{341 A}{630}-3 \sin (1)+\frac{11 \cos (1)}{3}$$ $$A=-\frac{210}{341} (11 \cos (1)-9 \sin (1))$$