Problem with using variable of For

Hello I have problem with for. I made for trying easy program which should demonstrate my problem.
function [p,j]=test
Q_q=[-0.3,-0.6,-0.3,0,0,0,0.3,0.3,0.6];
Delta=0.3;
place=1;
j=0;
for i=-0.9:Delta:0.9
if((length(find(Q_q==i)))==0)
j=j+1;
end
p(place,1)=(length(find(Q_q==i)));
p(place,2)=i;
if(p(place)>0)
place=place+1;
end
end
end
My problem is that length(find(Q_q==i)) doesn´t work. I mean if will write just
length(find(Q_q==-0,3))
answer is 2 but if I am going step by step all the way in the loop in moment where i=-0.3 then length(find(Q_q==i)) is still zero.
Can somebody tell me how where is the problem? And how to correct it?

 采纳的回答

NEVER test for exact equality of floating point numbers. Because, for example, it is impossible to store the number 0.3 EXACTLY as a floating point number. Remember that numbers are stored in a BINARY form. So just as you cannot write 1/3 exactly as a decimal, you cannot write the fraction 3/10 exactly in binary.
Use a tolerance. Something like
abs(Q_q - -0.3) < tol

更多回答(0 个)

类别

在 帮助中心 和 File Exchange 中查找有关 Introduction to Installation and Licensing 的更多信息

产品

标签

Community Treasure Hunt

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

Start Hunting!

Translated by