floating point precision

3 visualizzazioni (ultimi 30 giorni)
prateek
prateek il 9 Apr 2012
I am getting three kind of values for a variable (say vmax) after running my code. First value is 1. Second value is 1.0000 Third value is <1 I applied if else statements here as follows :
if vmax>=1
figure(1);
z=imread('C:\Program Files (x86)\MATLAB71\work\success.jpg');
imshow(z);
else
figure(2);
z=imread('C:\Program Files (x86)\MATLAB71\work\fail.jpg');
imshow(z);
end
As 1.0000 is slightly greater than 1 and I need same output for vmax=1 and vmax = 1.0000
But for few inputs which are giving vmax = 1.0000 , the if else works properly while for the other inputs which are giving vmax = 1.0000 , the if else executes "else" part. I am not getting why is this happening? For the same value of vmax, sometimes if else works the way it should while other times it works maliciously. Please help me.

Risposta accettata

James Tursa
James Tursa il 10 Apr 2012
E.g.,
>> X = 1
X =
1
>> Y = X + eps(X)
Y =
1.0000
>> Z = X - eps(X)
Z =
1.0000
>> num2strexact(X)
ans =
1
>> num2strexact(Y)
ans =
1.0000000000000002220446049250313080847263336181640625
>> num2strexact(Z)
ans =
0.9999999999999997779553950749686919152736663818359375
X, Y, and Z all print as 1 or 1.0000, but they are in fact different. You can find num2strexact here:
href=""<http://www.mathworks.com/matlabcentral/fileexchange/22239-num2strexact-exact-version-of-num2str</a>>

Più risposte (2)

Sean de Wolski
Sean de Wolski il 9 Apr 2012
I'm not toally clear on your question. If you're looking to see if something is close to 1,
isclose21 = abs(x-1)<1^-10; %is absolute difference between x and 1 less than 1e-10?

Walter Roberson
Walter Roberson il 9 Apr 2012

Categorie

Scopri di più su Data Types in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by