How to tell if a value is an integer?

9 views (last 30 days)
I have a for loop and this is an example of an iteration within the loop:
x=725*(77/29)
if x==floor(x)
a=1
else
a=0
end
where i am trying to see if x is an integer. a=1 is true which should apply to this since x=1925 however when I run the code it does a=0. How can i fix this?

Accepted Answer

Stephen23
Stephen23 on 4 Mar 2020
Edited: Stephen23 on 4 Mar 2020
"...which should apply to this since x=1925 ..."
Nope. Its actual value is:
>> x = 725*(77/29);
>> fprintf('%.40f\n',x)
1925.0000000000002273736754432320594787597656
The difference is:
>> 1925-x
ans = -2.27373675443232e-13
Clearly your operations accumulate some floating point error. The answer to your question is: change your algorithm so that you are not checking for exact equality between two binary floating point numbers. For example, check the absolute difference against some suitable tolerance value:
abs(A-B)<tol
Read more about binary floating point numbers:
This is worth reading as well:

More Answers (2)

James Tursa
James Tursa on 4 Mar 2020
Welcome to the world of floating point arithmetic. (77/29) cannot be represented exactly in IEEE double precision arithmetic, so any calculations that use this will be subject to small round-off errors.
>> num2strexact(725*(77/29))
ans =
1.925000000000000227373675443232059478759765625e3
>> num2strexact((725*77)/29)
ans =
1.925e3
You will need to rearrange the calculation and/or do the comparison within some tolerance.

David Hill
David Hill on 4 Mar 2020
if abs(x-floor(x))<1e-10

Categories

Find more on Elementary Math in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!