Advertisement
Guest User

Untitled

a guest
May 25th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Octave 2.13 KB | None | 0 0
  1. global iteartions = 0;
  2.  
  3. function ftmin = f(x)
  4.     global iteartions;
  5.     iteartions += 1;
  6.      %ftmin = (cos((3*x.^5 - 10*x + 10^(1./3) - 2 - 10*sqrt(2))./ 10) + atan((10*x.^5 - 10*sqrt(5)*x.^4 + 10*x.^3 + 3*x.^2 - 3*sqrt(5)*x + 1)./(2*x.^2 - 2*sqrt(5)*x + 2)));
  7.      %ftmin = -ftmin;
  8.      ftmin = (sin(x + 0.77)).^4;
  9. end
  10.  
  11. function a = gold_search(a, b, iter)
  12.     fa = NaN;
  13.     fb = NaN;
  14.     tau = (sqrt(5) - 1) / 2;
  15.     l = b - a;
  16.     x1 = b - tau * l;
  17.     x2 = a + tau * l;
  18.     f1 = f(x1);
  19.     f2 = f(x2);
  20.     i = 0;
  21.     while 1
  22.         if (i >= iter)
  23.             break
  24.         else
  25.             i += 1;
  26.             if (f1 <= f2)
  27.                 b = x2; fb = f2;
  28.                 l = b - a;
  29.  
  30.                 x2 = x1;
  31.                 f2 = f1;
  32.  
  33.                 x1 = b - tau*l;
  34.                 f1 = f(x1);
  35.             else
  36.                 a = x1; fa = f1;
  37.                 l = b - a;
  38.  
  39.                 x1 = x2;
  40.                 f1 = f2;
  41.  
  42.                 x2 = a + tau*l;
  43.                 f2 = f(x2);
  44.             end
  45.         end
  46.     end
  47. end
  48.  
  49. function [x,y] = newton(a, b, epsilon, iter)
  50.     h = 1e-5;
  51.     x = gold_search(a, b, iter);
  52.     %x = (a+b)/2;
  53.     y = f(x);
  54.     f2 =  (f(x - h) - 2*f(x) + f(x + h)) / (h.^2);
  55.     while 1
  56.       plot(x, f(x), 'k');
  57.       fa = f(x - h);
  58.       fb = f(x + h);
  59.       f1 = (fb - fa) / (2*h);
  60.       %printf('f1: %.16f', f1);
  61.       if abs(f1) < epsilon
  62.         printf('x = %d\n', x);
  63.         break
  64.       end
  65.       fm = f(x);
  66.       f2 = (fa - 2*fm + fb) / (h^2);
  67.       x = x - f1/f2;
  68.       y = f(x);
  69.       if x < a || x > b
  70.             printf('Error: x = %d\n', x);
  71.             break
  72.         end
  73.     end
  74. end
  75.  
  76. a = -1.0;
  77. b = 0.0;
  78.  
  79. iteartions = 0;
  80. hold on
  81. [x_min, y_min] = newton(a, b, 1e-6, 1);
  82. printf('x_min: %.16f, y_min: %.16f\n', x_min, y_min)
  83. err4 = x_min + 0.77;
  84. printf('err4: %.10f \n', err4)
  85. iteartions
  86. plot(a:0.05:b, f(a:0.05:b))
  87. plot(x_min, y_min, 'ro')
  88. hold off
  89.  
  90.  
  91. iteartions = 0;
  92. disp('')
  93. disp('fminbnd');
  94. [x_min, y_min, _, _ ] = fminbnd(@f, a, b, optimset('TolX',1e-6));
  95. printf('x_min: %.16f, y_min: %.16f\n', x_min, y_min)
  96. x_min
  97. y_min
  98. iteartions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement