Problem with if function and decimal numers
5 次查看(过去 30 天)
显示 更早的评论
Good evening, i have a problem with this code:
a=1:0.1:2;
b=0.1;
for i=1:1:10
angoloutile(i)=a(i);
end
for j=1:1:10
integ = fix(angoloutile(j)) ;
fract = abs(angoloutile(j)- integ);
if fract == b
angoloutile(j)=angoloutile(j)+0.5
end
end
for k=1:1:10
angoloutile(k)
end
it doesn't take the IF function
if fract == b
but i'm sure that angoloutile(2) is 1.1 Thanks
0 个评论
采纳的回答
Image Analyst
2014-1-13
The problem was using fix instead of rounding. Try this where I use int32() to cast to the nearest integer. I also cleaned up your if to make it more efficient and reduce the number of if tests by a factor of 10.
a=1:0.1:2;
for i=1:1:10
angoloutile(i)=a(i);
end
for j=1:1:10
integ = fix(angoloutile(j));
fract = abs(angoloutile(j)- integ);
fract=fract*10;
deci=int32(fract);
fprintf('j = %d, angoloutile(j) = %f, integ = %d, fact = %f, deci = %d\n', ...
j, angoloutile(j), integ, fract, deci);
if deci == 1
angoloutile(j)=angoloutile(j)+0.5;
elseif deci == 2
angoloutile(j)=angoloutile(j)-0.08;
elseif deci == 3
angoloutile(j)=angoloutile(j)-0.12;
elseif deci == 4
angoloutile(j)=angoloutile(j)-0.16;
elseif deci == 5
angoloutile(j)=angoloutile(j)-0.20;
elseif deci == 6
angoloutile(j)=angoloutile(j)-0.24;
elseif deci == 7
angoloutile(j)=angoloutile(j)-0.28;
elseif deci == 8
angoloutile(j)=angoloutile(j)-0.32;
elseif deci == 9
angoloutile(j)=angoloutile(j)-0.36;
end
end
% Print to command window.
angoloutile
更多回答(1 个)
Amit
2014-1-13
The issue is very small difference in floating point numbers, like 1.00000 and 1.0000000001. There is negligible difference however they are not equal. You can do something like:
tol = 1e-6;
if (fract-b) < tol
This will work.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!