Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scilab 2.19 KB | None | 0 0
  1. clear;
  2. clc;
  3. a=0.5;
  4. b=2;
  5. r=4;
  6. n_max=50;
  7. h=0.001;
  8. exit_code=0;
  9. function y=f(x);
  10.     y=(x^2-3)*sin(x);
  11. endfunction;
  12.  
  13. function y=fp(x,h);
  14.     y=(f(x+h)-f(x))/h;
  15. endfunction;
  16.  
  17. function y=fpp(x,h);
  18.     y=(fp(x+h,h)-fp(x,h))/h;
  19. endfunction;
  20.  
  21. n=1;
  22. X(1)=a;
  23.  
  24. if f(a)*f(b)<0 then
  25.     while(~(fp(a,h)*fp(b,h)>0 & fpp(a,h)*fpp(b,h)>0))
  26.         //metoda połowienia
  27.         if n<n_max then
  28.             n=n+1;
  29.             x(n)=(a+b)/2;
  30.             if abs(x(n)-x(n-1))<10^(-r) then
  31.                 exit_code=3;
  32.                 break;
  33.             else
  34.                 if f(x(n))==0 then
  35.                     exit_code=4;
  36.                     break;
  37.                 else
  38.                     if f(a)*f(x(n))<0 then
  39.                         b=x(n);
  40.                     else
  41.                         a=x(n);
  42.                     end;          
  43.                 end;      
  44.             end;
  45.         else
  46.             exit_code=2;
  47.         end;
  48.     end;
  49.     //metoda reguly falsi
  50.     // zmienić na metodę siecznych
  51.     if (exit_code==0 & n<n_max) then
  52.         n=n+1;
  53.         //to zmienić żeby liczyło n+2 i n+1
  54.         if fp(a,h)*fpp(a,h)<0 then
  55.             x(n)=b;
  56.             n=n+1;
  57.             x(n)=a;
  58.         else
  59.             x(n)=a;
  60.             n=n+1;
  61.             x(n)=b;
  62.         end;
  63.         while (n<n_max)
  64.             n=n+1;
  65.             //tu zmienic żeby używało n+2 i n+1
  66.             x(n)=x(n-1)-f(x(n-1))*(x(n-1)-x(n-2))/(f(x(n-1))-f(x(n-2)));
  67.             if abs(x(n)-x(n-1))<10^(-r) then
  68.                 exit_code=3;
  69.                 break;
  70.             end;  
  71.         end;
  72.         if (exit_code==0) then
  73.             exit_code=2;
  74.         end;
  75.     else
  76.         exit_code=2;
  77.     end;
  78. else
  79.      exit_code=1;
  80. end;
  81.  
  82. select exit_code
  83. case 1 then
  84.     disp("Niespełnione założenia metody połowienia");
  85. case 2 then
  86.     disp("Przekroczona maksymalna liczba iteracji"+string(n_max));
  87. case 3 then
  88.     disp("Osiągnięto dokładność rzędu 10^(" + string(-r)+")");
  89.     disp("x("+string(n)+")= "+string(x(n)));
  90. case 4 then
  91.     disp("Osiągnięto dokładną wartość pierwiastka");
  92.     disp("x("+string(n)+")= "+string(x(n)));
  93. else
  94.     disp("Wystąpił błąd");
  95. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement