Problem with if function and decimal numers
6 ビュー (過去 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!