How to tell if a value is an integer?
Mostra commenti meno recenti
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
Più risposte (2)
James Tursa
il 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
il 4 Mar 2020
if abs(x-floor(x))<1e-10
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!