c - unexpected floating point arthimatic -
some time ago have posted question here , got know floating point values should not compared double values due varying precision , may not predictable results always. stumbled across code comparison between 2 or more floating point numbers resulted in quite strange behavior.
here code came across:
#include<stdio.h> int main() { float a=0.0f; int i; for(i=0;i<10;i++) a=a+0.1f; if(a==1.0f) printf("true\n"); else printf("false\n"); a=0.0f; for(i=0;i<5;i++) a=a+0.2f; if(a==1.0f) printf("true\n"); else printf("false\n"); } the code gave me false , true output startled me quite bit. why behavior? if there loss of precision number 0.1f not being represented precisley in binary representation , adding time , again causing summation lesser 1.0f? same should true next loop right? how far can trust floating point arthimatic?
you assume a+0.2 equal a+0.1+0.1. not case (because of rounding errors) values of a, case others. example, when a==0 both equal, if a smallest number a+0.1==a both different.
see code:
#include<stdio.h> int main() { float a=0.0f; int i; for(i=0;i<10;i++){ if (a+0.1f+0.1f==a+0.2f) printf("i=%d, equal!\n",i); else printf("i=%d, delta=%.10f\n",i,(a+0.1f+0.1f)-(a+0.2f)); a=a+0.1f; } return 0; } the output is:
i=0, equal! i=1, equal! i=2, equal! i=3, equal! i=4, equal! i=5, delta=0.0000000596 i=6, delta=0.0000000596 i=7, delta=0.0000000596 i=8, equal! i=9, equal!
Comments
Post a Comment