Skip site navigation (1)Skip section navigation (2)
Date:      Mon, 15 Jan 2018 15:45:51 +0100
From:      Hans Petter Selasky <hps@selasky.org>
To:        Yuri Pankov <yuripv@icloud.com>, freebsd-current <freebsd-current@freebsd.org>
Subject:   Re: inconsistent for() and while() behavior when using floating point
Message-ID:  <379d470c-480b-96d7-819b-873cc3100fc7@selasky.org>
In-Reply-To: <6c423dbf-cd85-3c93-41e4-3362c06dfbb7@icloud.com>
References:  <6c423dbf-cd85-3c93-41e4-3362c06dfbb7@icloud.com>

next in thread | previous in thread | raw e-mail | index | archive | help
On 01/15/18 15:38, Yuri Pankov wrote:
> Hi,
> 
> Looking at https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=217149, I 
> noticed that it isn't a seq(1) problem per se, rather for() and while() 
> loops behaving inconsistently while using floating point, i.e.:
> 
>          double i;
> 
>          for (i = 1; i <= 2.00; i += 0.1)
>                  printf("%g\n", i);
> 
> would produce:
> 
>          1
>          ...
>          1.9
> 
> but:
> 
>          double i;
> 
>          for (i = 1; i <= 2; i += 0.2)
>                  printf("%g\n", i);
> 
> would correctly end with 2:
> 
>          1
>          ...
>          2
> 

Hi,

The decimal value "0.2" is the same like the fraction "1/5", which 
cannot be represented by a float nor double without rounding error. The 
more times you iterate the bigger the error becomes.

When you compare an integer with a float rounding happens. Check this out:

if ((int)(float)0.999999999999999999999 >= (int)1)
         printf("OK\n");

Sequences using floating point should technically only use steps which 
can be written like this: "remainder * pow(2, -shift)".

--HPS



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?379d470c-480b-96d7-819b-873cc3100fc7>