Advertisement
Guest User

Untitled

a guest
Jul 20th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.73 KB | None | 0 0
  1. function giaiPTNewton()
  2.     syms x;
  3.     disp('Giai phuong trinh f(x)=0 bang phuong phap Newton...');
  4.     f = input('Nhap ham f(x) = ');
  5.     fprintf('\n');
  6.     disp('Nhap khoang [a b]:');
  7.     a = input('a = ');
  8.     b = input('b = ');
  9.     fprintf('\n');
  10.     slv = 1;
  11.     % Kiem tra dieu kien hoi tu
  12.    
  13.     if subs(f,x,a)*subs(f,x,b)>=0
  14.         fprintf('Khoang cach ly nghiem khong hop le');
  15.         slv = 0;
  16.     elseif isreal(solve(diff(f,x)))
  17.         x_ = solve(diff(f,x));
  18.         for i=1:length(x_)
  19.             if isreal(x_(i)) && (a<=x_(i)) && (x_(i)<=b)
  20.                 fprintf('Dao ham cua ham so co diem bang 0');
  21.                 slv = 0;
  22.             end;
  23.         end;
  24.     end;
  25.     if slv
  26.         % Tim x0 theo Fourier
  27.         f1 = diff(f,x);
  28.         f2 = diff(f,x,2);
  29.         if subs(f,x,a)*subs(f2,x,a)>0
  30.             x0 = a;
  31.         else x0 = b;
  32.         end;
  33.        
  34.         % Xay dung day lap
  35.         n = input('Nhap so lan lap: n = ');
  36.         xCurrent = x0;
  37.         xBefore = 0;
  38.         for i=1:n
  39.             xBefore = xCurrent;
  40.             xCurrent = xCurrent - subs(f,x,xCurrent)/subs(f1,x,xCurrent);
  41.         end;
  42.         xDraw = linspace(a-2,b+2);
  43.         yDraw = subs(f,x,xDraw);
  44.         fprintf('Nghiem x%d = %f\n',n,xCurrent);
  45.         yBefore = subs(f,x,xBefore);
  46.         plot(xDraw,yDraw,'b-');
  47.         hold on;
  48.         % Tim tiep tuyen tai diem x(n-1)
  49.         dif = subs(f1,x,xBefore);
  50.         xa = a-2;
  51.         syms y;
  52.         ya = solve(y-yBefore-dif*(xa-xBefore),y);
  53.         xb = b+2;
  54.         yb = solve(y-yBefore-dif*(xb-xBefore),y);
  55.         plot([xa,xb],[ya,yb],'-');
  56.         grid on;
  57.         plot(xBefore,yBefore,'r*');
  58.         plot(xCurrent,0,'g*');
  59.     end;
  60.    
  61.    
  62.        
  63. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement