Why 0.35 divide 0.001 return double, and 0.34 divide 0.001 return int.
Afficher commentaires plus anciens
simple codes:
>> 0.35/0.001
ans =
350.0000
and
>> 0.34/0.001
ans =
340
I'm curious why this is. If use 0.351/0.001, it return 351.0000, and 0.352/0.001, it return 352.
1 commentaire
zongxian
le 17 Mar 2020
Réponse acceptée
Plus de réponses (2)
James Tursa
le 16 Mar 2020
Modifié(e) : James Tursa
le 16 Mar 2020
Welcome to the world of floating point arithmetic. In one case, the result is 340 exactly so it prints without any trailing 0's after the decimal point. In the other case, the result is not 350 exactly so it prints with trailing 0's after the decimal point. This is all a result of the fact that the original values you are using cannot be represented exactly in IEEE double precision, so you get round-off errors that behave slightly differently in one case vs the other case. See this link for more discussion on this:
E.g.,
>> fprintf('%.50f\n',0.001)
0.00100000000000000002081668171172168513294309377670
>> fprintf('%.50f\n',0.35)
0.34999999999999997779553950749686919152736663818359
>> fprintf('%.50f\n',0.35/0.001)
349.99999999999994315658113919198513031005859375000000
>> fprintf('%.50f\n',0.34)
0.34000000000000002442490654175344388931989669799805
>> fprintf('%.50f\n',0.34/0.001)
340.00000000000000000000000000000000000000000000000000
>>
>> 350 == 0.35/0.001
ans =
logical
0
>> 340 == 0.34/0.001
ans =
logical
1
Subhamoy Saha
le 16 Mar 2020
Not sure why it is showing like that but the case is both are double.
a=0.351/.001
whos a
b=0.352/.001
whos b
Catégories
En savoir plus sur Mathematics dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!