for loop results in NaN after 453 loops
4 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Geoff
2012 年 3 月 19 日
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 件のコメント
Geoff
2012 年 3 月 20 日
Have edited my answer to explain. Would write it here, but the comments don't allow code-formatting.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Entering Commands についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!