Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- global iteartions = 0;
- function ftmin = f(x)
- global iteartions;
- iteartions += 1;
- %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)));
- %ftmin = -ftmin;
- ftmin = (sin(x + 0.77)).^4;
- end
- function a = gold_search(a, b, iter)
- fa = NaN;
- fb = NaN;
- tau = (sqrt(5) - 1) / 2;
- l = b - a;
- x1 = b - tau * l;
- x2 = a + tau * l;
- f1 = f(x1);
- f2 = f(x2);
- i = 0;
- while 1
- if (i >= iter)
- break
- else
- i += 1;
- if (f1 <= f2)
- b = x2; fb = f2;
- l = b - a;
- x2 = x1;
- f2 = f1;
- x1 = b - tau*l;
- f1 = f(x1);
- else
- a = x1; fa = f1;
- l = b - a;
- x1 = x2;
- f1 = f2;
- x2 = a + tau*l;
- f2 = f(x2);
- end
- end
- end
- end
- function [x,y] = newton(a, b, epsilon, iter)
- h = 1e-5;
- x = gold_search(a, b, iter);
- %x = (a+b)/2;
- y = f(x);
- f2 = (f(x - h) - 2*f(x) + f(x + h)) / (h.^2);
- while 1
- plot(x, f(x), 'k');
- fa = f(x - h);
- fb = f(x + h);
- f1 = (fb - fa) / (2*h);
- %printf('f1: %.16f', f1);
- if abs(f1) < epsilon
- printf('x = %d\n', x);
- break
- end
- fm = f(x);
- f2 = (fa - 2*fm + fb) / (h^2);
- x = x - f1/f2;
- y = f(x);
- if x < a || x > b
- printf('Error: x = %d\n', x);
- break
- end
- end
- end
- a = -1.0;
- b = 0.0;
- iteartions = 0;
- hold on
- [x_min, y_min] = newton(a, b, 1e-6, 1);
- printf('x_min: %.16f, y_min: %.16f\n', x_min, y_min)
- err4 = x_min + 0.77;
- printf('err4: %.10f \n', err4)
- iteartions
- plot(a:0.05:b, f(a:0.05:b))
- plot(x_min, y_min, 'ro')
- hold off
- iteartions = 0;
- disp('')
- disp('fminbnd');
- [x_min, y_min, _, _ ] = fminbnd(@f, a, b, optimset('TolX',1e-6));
- printf('x_min: %.16f, y_min: %.16f\n', x_min, y_min)
- x_min
- y_min
- iteartions
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement