Matlab (R2015a) seems to be computing wrongly a simple recurrent sum. Below is a simple code that shows it. I get that Answer='no', AnResp='yes' however t4(401)=0.012. Does anyone have an idea of what is going on here?

t4(1)=0;
Dt4=3.0e-5;
for kk=2:401
t4(kk)=t4(kk-1)+Dt4;
end
if t4(401)==0.012
Answer='yes'
else
Answer='no'
end
if t4(401)>0.012
AnResp='yes'
else
AnResp='no'
end

 采纳的回答

It is not that MATLAB has computed incorrectly. It is that you don't appreciate how numbers are stored in a floating point form.
It does not equal 0.012. In fact, 0.012 does not equal 0.012, since you cannot represent 0.012 exactly in a binary representation of floating point arithmetic.

3 个评论

Thank you for your answer. I see that the issue is related to the representation of the numbers in floating point form. I would appreciate any suggestions as to how to avoid situations where the binary representation of floating point arithmetic can lead to errors in the code.

请先登录,再进行评论。

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by