From owner-freebsd-current@freebsd.org Mon Jan 15 14:48:44 2018 Return-Path: Delivered-To: freebsd-current@mailman.ysv.freebsd.org Received: from mx1.freebsd.org (mx1.freebsd.org [IPv6:2001:1900:2254:206a::19:1]) by mailman.ysv.freebsd.org (Postfix) with ESMTP id 0FF8FEA772C for ; Mon, 15 Jan 2018 14:48:44 +0000 (UTC) (envelope-from hps@selasky.org) Received: from mail.turbocat.net (turbocat.net [88.99.82.50]) (using TLSv1.2 with cipher ECDHE-RSA-AES256-GCM-SHA384 (256/256 bits)) (Client did not present a certificate) by mx1.freebsd.org (Postfix) with ESMTPS id CBDF278DF0 for ; Mon, 15 Jan 2018 14:48:43 +0000 (UTC) (envelope-from hps@selasky.org) Received: from hps2016.home.selasky.org (unknown [62.141.128.70]) (using TLSv1.2 with cipher ECDHE-RSA-AES128-GCM-SHA256 (128/128 bits)) (No client certificate requested) by mail.turbocat.net (Postfix) with ESMTPSA id 3894826009E; Mon, 15 Jan 2018 15:48:41 +0100 (CET) Subject: Re: inconsistent for() and while() behavior when using floating point To: Yuri Pankov , freebsd-current References: <6c423dbf-cd85-3c93-41e4-3362c06dfbb7@icloud.com> From: Hans Petter Selasky Message-ID: <379d470c-480b-96d7-819b-873cc3100fc7@selasky.org> Date: Mon, 15 Jan 2018 15:45:51 +0100 User-Agent: Mozilla/5.0 (X11; FreeBSD amd64; rv:52.0) Gecko/20100101 Thunderbird/52.5.2 MIME-Version: 1.0 In-Reply-To: <6c423dbf-cd85-3c93-41e4-3362c06dfbb7@icloud.com> Content-Type: text/plain; charset=utf-8; format=flowed Content-Language: en-US Content-Transfer-Encoding: 8bit X-BeenThere: freebsd-current@freebsd.org X-Mailman-Version: 2.1.25 Precedence: list List-Id: Discussions about the use of FreeBSD-current List-Unsubscribe: , List-Archive: List-Post: List-Help: List-Subscribe: , X-List-Received-Date: Mon, 15 Jan 2018 14:48:44 -0000 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