sashachca

euler

Oct 1st, 2018
467
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Octave 1.53 KB | None | 0 0
  1. function euler_T
  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.   y_me1 = euler_method(X, y0, h1);
  11.   y_me2 = euler_method(X, y0, h2);
  12.  
  13.   y_mi1 = euler_midpoint(X, y0, h1);
  14.   y_mi2 = euler_midpoint(X, y0, h2);
  15.  
  16.   i = 1;
  17.   printf('\n  I \n\n h1 = 0.1 \n\n  X   Y');
  18.   for j = X(1):h1:X(2)
  19.     printf('\n  %i   %i', j, y_me1(i));
  20.     i += 1;
  21.   endfor
  22.  
  23.   i = 1;
  24.   printf('\n\n  h2 = 0.01 \n');
  25.   for j = X(1):h2:X(2)
  26.     printf('\n  %i   %i', j, y_me2(i));
  27.     i += 1;
  28.   endfor
  29.  
  30.   i = 1;
  31.   printf('\n\n\n  II \n\n h1 = 0.1 \n\n');
  32.   for j = X(1):h1:X(2)
  33.     printf('\n  %i   %i', j, y_mi1(i));
  34.     i += 1;
  35.   endfor
  36.  
  37.   i = 1;
  38.   printf('\n\n  h2 = 0.01 \n');
  39.   for j = X(1):h2:X(2)
  40.     printf('\n  %i   %i', j, y_mi2(i));
  41.     i += 1;
  42.   endfor
  43.  
  44.  
  45.   plot(X(1):h1:X(2), y_me1(1:end-1), 'r', X(1):h2:X(2), y_me2(1:end-1), 'b', X(1):h1:X(2), y_mi1, 'g', X(1):h2:X(2), y_mi2, 'y');
  46.     title('    red - h1; blue - h2, green - h1 & pereschet, yellow - h2 & pereschet   '), grid on
  47.  
  48.  
  49.  
  50. end
  51.  
  52.  
  53.  
  54. function y = euler_method(X, y_i, h)
  55.   y = [y_i];
  56.   i = 1;
  57.  
  58.   for x = X(1):h:X(2)
  59.  
  60.     y(i+1) = y(i) + h*f(x, y(i));
  61.     i += 1;
  62.  
  63.   endfor
  64.  
  65. endfunction
  66.  
  67.  
  68. function y = euler_midpoint(X, y_i, h)
  69.   y = [y_i];
  70.   i = 1;
  71.  
  72.   for x = X(1):h:X(2)-h
  73.  
  74.     y(i+1) = y(i) + h/2*( f(x, y(i)) + f(x+h, y(i) + h*f(x, y(i))) );
  75.     i += 1;
  76.  
  77.   endfor
  78.  
  79. endfunction
  80.  
  81.  
  82. function f = f(x, y)
  83.  
  84.   f = (-y + x*sin(x)) / x;
  85.  
  86. endfunction
Advertisement
Add Comment
Please, Sign In to add comment