How to tell if a value is an integer?

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?

 Risposta accettata

Stephen23
Stephen23 il 4 Mar 2020
Modificato: Stephen23 il 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:

Più risposte (2)

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.

Categorie

Scopri di più su Loops and Conditional Statements in Centro assistenza e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by