Problem with if function and decimal numers
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Nicola
el 13 de En. de 2014
Comentada: Nicola
el 13 de En. de 2014
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 comentarios
Respuesta aceptada
Image Analyst
el 13 de En. de 2014
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
Más respuestas (1)
Amit
el 13 de En. de 2014
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.
Ver también
Categorías
Más información sobre Whos en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!