Why am I getting inf even though there is no divide by zero?
12 views (last 30 days)
Show older comments
When I execute the folowing code if I take the value of 'k' as 2 or 3, the answer for any value for 'alpha' array becomes inf if the quotient is greater than 1. I am also not able to take the sum of the elements of array 's' as that gives this error: 'Array indices must be positive integers or logical values.'. Can someone tell me what is causing this?
A=[14.5463 14.224 14.2043]
B=[2940.46 2945.467 2972.64]
C=[273.22 224 209]
X=[0.25 0.35 0.4]
P=80
n=3
to=0
Pi_sat=[0 0 0]
k=1
alpha=[0 0 0]
s=[0 0 0]
y=[0 0 0]
for i=1:n
Ti_sat(i)=B(i)/(A(i)-log(P))+C(i)
to=to+X(i)*Ti_sat(i)
end
while 1
for i=1:n
Pi_sat(i)=A(i)-B(i)/(to+C(i))
alpha(i)=Pi_sat(i)/Pi_sat(k)
end
s=X.*alpha
Pk_sat=P/sum(s)
tnew=B(k)/(A(k)-log(Pk_sat))+C(k)
e=abs((tnew-to)/to)
if(e<0.001)
break
end
to=tnew
end
fprintf('\nTemperature=%f',tnew)
for i=1:n
y(i)=X(i)*Pi_sat(i)/P
fprintf('\ny(%i)=%f',i,y(i))
end
0 Comments
Accepted Answer
Matt J
on 11 Dec 2022
Edited: Matt J
on 11 Dec 2022
I am also not able to take the sum of the elements of array 's' as that gives this error: 'Array indices must be positive integers or logical values
You have created a variable names "sum" somewhere, so that now Matlab is treating it as a variable.
Other than that, the infs are indeed caused by a divide by zero condition, see below.
while 1
for i=1:n
Pi_sat(i)=A(i)-B(i)/(to+C(i));
alpha(i)=Pi_sat(i)/Pi_sat(k);
if isinf(alpha(i))
Pi_sat([i,k])
keyboard
end
end
end
More Answers (2)
Steven Lord
on 11 Dec 2022
To determine why an Inf is generated even though you don't believe there should be any division by zero performed by your code, set an error breakpoint to stop when a NaN or Inf value is generated then run your code. If MATLAB stops at a line of code, check the values on that line to see if they contain the values you expect them to contain. If they don't, set breakpoints on earlier and earlier lines of code and rerun your code to allow you to look at the variables as your code runs and hopefully determine when and why the differences between what you expect and what's actually stored in the variables are introduced.
1 Comment
Jai
on 6 Nov 2023
But, when the value is too large to get overflowed it will return "inf". how to handle this please help
Thanks.
See Also
Categories
Find more on Matrices and Arrays 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!