for loop results in NaN after 453 loops
1 view (last 30 days)
Show older comments
I am trying to approximate an infinte sum expression. I dicovered that for whatever reason the sum becomes NaN after 453 loops.
Here is a sample of my code (just the portion I am having trouble with):
L = 1; H = 1; T0 = 373; T1 = 473;
theta_center = 0;
for p = 1:452 theta_center = theta_center + ((-1)^(p+1)+1)/p*sin(p*pi/2)*sinh(p*pi/L*H/2)/sinh(p*pi*H/L);
end
When I set the for loop to be any number less than 453, theta_center is a number, but when I set the for loop to any number greater 452, theta center becomes NaN.
Any help?
0 Comments
Accepted Answer
Geoff
on 19 Mar 2012
Because the result of the first sinh term becomes Inf:
> p = 452;
> sinh(p*pi/L*H/2)
ans =
1.1169e+308
> p = 453;
> sinh(p*pi/L*H/2)
ans =
Inf
Note that the second sinh() term becomes Inf much sooner, but you only get NaN once you have divided Inf by Inf.
Do you want to treat p*pi as cyclic? Then use:
mod(p,2)*pi
EDIT: from comments below
I generated each iteration of your loop into a vector and then did a cumulative sum.
vals = [];
for p = 1:452
vals(p) = ((-1)^(p+1)+1)/p*sin(p*pi/2)*sinh(p*pi/L*H/2)/sinh(p*pi*H/L);
end
vals = cumsum(vals);
% What is the last non-zero index?
idx = find( vals ~= 0, 1, 'last' );
That finds the real zeros, but it will be effectively zero much sooner:
% What is the last near-zero index?
idx = find( abs(vals) > 1e-8, 1, 'last' );
Without hard-coding any loop sizes, you can just use a while-loop with some terminating criteria: ie the most recent non-zero term being added to theta_center is sufficiently small.
5 Comments
Geoff
on 20 Mar 2012
Have edited my answer to explain. Would write it here, but the comments don't allow code-formatting.
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements 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!