Advertisement
sashachca

Euler

Sep 25th, 2018
564
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Octave 0.81 KB | None | 0 0
  1. function euler
  2.  
  3.   % y' = (-y+x*sin(x))/x; y(1) = 0.3011687, x = [1, 2]
  4.  
  5.   x = [1, 2];
  6.   y0 = 0.3011687;
  7.   h1 = 0.1;
  8.   h2 = 0.01;
  9.  
  10.   printf('\n  I \n\n h1 = 0.1 \n y = %i', euler_method(x, y0, h1));
  11.   printf('\n\n h2 = 0.01 \n y = %i\n\n\n', euler_method(x, y0, h2));
  12.  
  13.   printf('  II \n\n h1 = 0.1 \n y = %i', euler_midpoint(x, y0, h1));
  14.   printf('\n\n h2 = 0.01 \n y = %i\n\n\n', euler_midpoint(x, y0, h2));
  15.  
  16.  
  17. end
  18.  
  19.  
  20.  
  21. function y = euler_method(x, y_i, h)
  22.  
  23.   for x = x(1):h:x(2)
  24.  
  25.     y = y_i + h*f(x, y_i);
  26.     y_i = y;
  27.  
  28.   endfor
  29.  
  30. endfunction
  31.  
  32.  
  33. function y = euler_midpoint(x, y_i, h)
  34.  
  35.   for x = x(1):h:x(2)-h
  36.  
  37.     y = y_i + h/2*( f(x, y_i) + f(x+h, y_i + h*f(x, y_i)) );
  38.     y_i = y;
  39.  
  40.   endfor
  41.  
  42. endfunction
  43.  
  44.  
  45. function f = f(x, y)
  46.  
  47.   f = (-y + x*sin(x)) / x;
  48.  
  49. endfunction
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement