# Category: Calculus
# Name: Linear approximation by a tangent graphically

function f(x) = sin(ln(x+1))^2;
df = SymbolicDerivative(f);

# Where to approximate
a = 2;

# The approximation
function lf(x) = df(a)*(x-a)+f(a);

function DoGraph(x) = (
  PlotCanvasFreeze();
  LinePlot(f,lf,[-0.5,5,-0.1,2]);
  LinePlotDrawLine(x,0,x,min(f(x),lf(x)),"color","orange");
  LinePlotDrawLine(x,min(f(x),lf(x)),x,max(f(x),lf(x)),"color","red");
  LinePlotDrawLine(-0.5,f(x),5,f(x),"color","black","thickness",1);
  LinePlotDrawLine(-0.5,lf(x),5,lf(x),"color","purple","thickness",1);
  PlotCanvasThaw();
  print("at x=" + x + "  error = |" + lf(x) + " - " + f(x) + "| = " + |lf(x)-f(x)|);
);

PlotWindowPresent(); # Make sure the window is raised

for x=2 to 5 by 0.0222 do (
  DoGraph(x);
  wait(0.003)
);
for x=5 to -0.5 by -0.0222 do (
  DoGraph(x);
  wait(0.06)
);
for x=-0.5 to 2 by 0.0222 do (
  DoGraph(x);
  wait(0.003)
);
