Infinite loop with golden search method
1 view (last 30 days)
Show older comments
Hi I want this code to spit out F = 10 when w = 0 at the maximum using the golden search method as shown by eliminating each w value until maximum is achieved. The starting upper and lower values are -1 and 1.
My trouble is Matlab does not understand 2*sin(5*w)/w = 2 when w = 0 not NaN Therefore my code is infinitely looping.
Can someone please help me solve this issue??
Below is the Code.
%Plots fourier transform. a=5; w=-a:a/100:a; F=2*sin(a*w)./w; plot(w,F)
r = 0.5*(sqrt(5)-1);
% Lower and upper limits
wlower = -1;
wupper = 1;
% Answer from golden-section search method
wgs = 0.5*(wlower + wupper);
% Error in result
werr = wupper - wlower;
% Values of x to be used to find minima
w1 = wlower + r*werr;
w2 = wlower + r^2*werr;
% Evaluate function at critical locations
F1 = 2*sin(a*wlower)./wlower;
F2 = 2*sin(a*wupper)./wupper;
% Relative error for stopping
err_rel = 1e-4;
% Absolute error for stopping
err_abs = 1e-8;
while (werr > wgs*err_rel && werr > err_abs) % Check which half of range the root is located
if F1 < F2
% Located in lower half, so reject upper half
wupper = w1ower;
% Error in result
werr = wupper - wlower;
w1 = w2;
F1 = F2;
w2 = wlower + r^2*werr;
F2 = 2*sin(a*wupper)./wupper;
else
% Located in upper half, so reject lower half
wlower = w2;
% Error in result
werr = wupper - wlower;
w2 = w1;
F2 = F1;
w1 = wlower + r*werr;
F1 = 2*sin(a*wlower)./wlower;
end
wgs = 0.5*(wlower + wupper);
end
0 Comments
Accepted Answer
Walter Roberson
on 30 Aug 2013
My trouble is Matlab does not understand 2*sin(5*w)/w = 2 when w = 0 not NaN
The limit of sin(p*x)/x as x approaches 0 is p, not 1.
If you need to avoid the NaN when dividing by 0, then use "if" to check the denominator before you do the division. Or use isnan() on the result to check to see if you got NaN.
0 Comments
More Answers (0)
See Also
Categories
Find more on Downloads in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!