clear
close

disp('               TANGENT PLANE APPROXIMATION  ')
disp(' ')

disp('                f(x,y) = (1-y^2)cos(x)        ')

f = inline('(1-y.^2).*cos(x) ', 'x', 'y');

x = linspace(-1,1,51);
y = x;
[X,Y] = meshgrid(x,y);
surf(X,Y,f(X,Y));colormap(gray);  shading interp;
%axis([-1,1.5, -1,1, 0, 1.8])
 axis equal
hold on

  plot3(x, -.4 +0*y, f(x,-.4), 'r')
  plot3(.2+0*x, y, f(.2, y), 'b')
  pause

  fx = inline('(y.^2 -1).*sin(x)', 'x', 'y');
  fy = inline('-2*y.*cos(x)', 'x', 'y');

  p = [.2, -.4, f(.2, -.4)];

  v = [1, 0, fx(.2, -.4)];
  w = [0, 1, fy(.2, -.4)];
  N = cross(v,w);
  arrow3(p, v,'r');
  arrow3(p, w, 'b');
  arrow3(p, N, 'k');
  pause

  disp('  ')
  disp(' Now we attach the tangent plane at the point (.2, -.4)  ')
  disp(' The tangent plane is the graph of the linear approximation ')
  disp(' ')
  disp('    l(x,y) = f(.2, -.4) + fx(.2, -.4)(x-.2) +fy(.2, -.4)(y+.4)  ')
  disp('           = .8233 -.1669(x-.2) + .7841(y+.4)  ')
  tplane(f, [.2, -.4])
  rotate3d on
  hold off
  pause


  disp(' ')
  disp(' Numerical properties of tangent plane approximation  ')
  disp(' We calculate the error E = f(x,y) - l(x,y) over different')
  disp(' squares centered at (.2, -.4)  ')
  l = inline(' .8233 -.1669*(x-.2) + .7841*(y+.4)', 'x', 'y');
  q = linspace(-.5, .5, 51); r = q;
  disp(' The max error |E| = |f(x,y) - l(x,y)| over the square Q')
  disp(' centered at (.2, -.4) with side = 1  is ')
  [Q,R] = meshgrid(q,r);
  E = f(Q +.2, R-.4) - l(Q +.2,R-.4);
  max(max(abs(E)))
  pause

  disp(' The max error over the square with side = 1/2 is ')
  E = f(.5*Q +.2, .5*R -.4) -l(.5*Q +.2, .5*R -.4);
  max(max(abs(E)))
  pause

  disp(' The max error over the square with side = .1/4  is ')

  E = f(.25*Q+.2, .25*R-.4 )- l(.25*Q+.2, .25*R-.4);
  max(max(abs(E)))
  pause
   
  disp(' The max error ove the square with side = 1/8 is ')
  
  E = f(.125*Q +.2, .125*R-.4) - l(.2+.125*Q, -.4+.125*R);
  max(max(abs(E)))
  
  

  hold off
  pause
  close


  

