Facebook
From radon, 3 Months ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 164
  1. function main()
  2.     % Dane
  3.     x0 = 1; % Początkowe przybliżenie
  4.     eps = 1e-8; % Precyzja
  5.  
  6.     % Wywołanie funkcji do znajdowania miejsca zerowego
  7.     result = find_zero(@func_to_solve, x0, eps);
  8.  
  9.     fprintf('Miejsce zerowe: %.8f\n', result);
  10.  
  11.     % Graficzne przedstawienie funkcji i miejsca zerowego
  12.     x_vals = linspace(result - 2, result + 2, 1000);
  13.     y_vals = func_to_solve(x_vals);
  14.  
  15.     figure;
  16.     plot(x_vals, y_vals, 'LineWidth', 2);
  17.     hold on;
  18.     plot(result, 0, 'ro', 'MarkerSize', 10, 'MarkerFaceColor', 'r');
  19.     title('Funkcja f(x) = 2^x - 4x i miejsce zerowe');
  20.     xlabel('x');
  21.     ylabel('f(x)');
  22.     grid on;
  23.     legend('f(x)', 'Miejsce zerowe', 'Location', 'Best');
  24. end
  25.  
  26. function y = func_to_solve(x)
  27.     y = 2^x - 4 * x;
  28. end
  29.  
  30. function result = find_zero(func, x0, eps)
  31.     x = x0;
  32.     k = 0;
  33.  
  34.     while true
  35.         y = g(x);
  36.         z = g(y);
  37.  
  38.         delta = ((y - x)^2) / z - 2 * y + x;
  39.         x_new = x - delta;
  40.  
  41.         if abs(delta) <= eps
  42.             result = x_new;
  43.             break;
  44.         end
  45.  
  46.         x = x_new;
  47.         k = k + 1;
  48.     end
  49. end
  50.  
  51. function y = g(x)
  52.     y = func_to_solve(x);
  53. end
  54.