Advertisement
MikecIT

goldenRatio

Nov 23rd, 2018
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 0.62 KB | None | 0 0
  1. function [x, fx] = goldenRatio(fun, a, b, tol)
  2.     c = (3 - sqrt(5)) / 2;
  3.  
  4.     x1 = a + c * (b - a); f1 = feval(fun, x1);
  5.     x2 = a + b - x1; f2 = feval(fun, x2);
  6.  
  7.     while abs(b - a) > tol
  8.         if f1 <= f2
  9.             b = x2;
  10.             x2 = x1;
  11.             f2 = f1;
  12.             x1 = a + c * (b - a);
  13.             f1 = feval(fun, x1);
  14.         else
  15.             a = x1;
  16.             x1 = x2;
  17.             f1 = f2;
  18.             x2 = b - c * (b - a);
  19.             f2 = feval(fun, x2);
  20.         end
  21.  
  22.         if f1 < f2
  23.             x = x1; fx = f1;
  24.         else
  25.             x = x2; fx = f2;
  26.         end
  27.     end
  28. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement