🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: gnu.gcc.help
Article #41952

Re: FP weirdness, i586,

#41952
From: Martin Ambuhl
Date: Mon, 29 Jan 1996 00:00
63 lines
2648 bytes
amish@data.uchicago.edu (Amish Dave)
in <DLtLuF.KEC@midway.uchicago.edu> asks:

>On a P133 running Linux1.2.13 with gcc-2.7.0, I get strange behavior with
>the code below.  Sparc2-SunOS-gcc2.6.3 and Alpha-DecUNIX2.3c-gcc2.7.0
>behave correctly with the same code.

"Behave correctly" is not another way of saying "what I expect."  Correct
behavior, according ISO 6.2.1.3, includes:

    "When a value of a floating type is converted to integral type, the
    fractional part is discarded."

When you evaluate 0.7 * 70 or 0.7 * (20+50), you are depending on the
level and type of optimization the compiler uses.  A "smart"
implementation may decide that it knows the result to be 49, but a
strong argument can be made that the correct result should be 48.  0.7
decimal is not expressible as n / pow(2.,k) where n and k are integers.
So it will be a repeating fraction.  In octal, this is
0.5 4631 4631 4631 ... Suppose a mantissa of 30 bits (10 octal digits).
If the implementation uses 0.5 4631 4631 4, then 0.7 *70 is 48; while
with 0.5 4631 4631 5, 0.7 *70 is 49.

[To make it easier, note that
    0.54 * 106 (octal) = 60.10 (octal) = 48.125 (decimal)
    0.55 * 106 (octal) = 61.16 (octal) = 49.21875  (decimal)]


>#include <stdio.h>
>main()
>{
>        int a = 20, b = 50, c;

>        c = (int)(0.7 * (a + b));
>        printf("c = %d\n", c);

>        c = (int)(0.7 * 70);
>        printf("c = %d\n", c);
>}

>When compiled without any options (gcc -o foo foo.c), on the Pentium, it
>prints out
>c = 48
>c = 49

>The correct output should be:
     ^^^^^^^
     wrong.  Correct outputs include 48 and 49.
>c = 49
>c = 49

>On Sparc-SunOS-2.6.3 or Alpha-DUnix3.2c-2.7.0 machines, it works correctly.
>I can get it to function correctly on the Pentium with -msoft-float, but...
                          ^^^^^^^^^
                          wrong.
>What's going on?

You haven't learned your early lessons in floating point arithmetic and
how to protect yourself from unexpected but correct results.
                                            
--
* Martin Ambuhl       net: mambuhl@ripco.com
* Chicago, IL (USA)    
Technical Details
Message-ID: <DLy66w.86E@rci.ripco.com>
Path: arc1-ca.pugleaf.net!unknown!not-for-mail

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: 11318c,85fd0dbb2adf1343,start
X-Google-Attributes: gid11318c,public
From: mambuhl@ripco.com (Martin Ambuhl)
Subject: Re: FP weirdness, i586,  
Date: 1996/01/29
Message-ID: <DLy66w.86E@rci.ripco.com>
X-Deja-AN: 137044125
sender: usenet@rci.ripco.com (Net News Admin)
x-nntp-posting-host: foley.ripco.com
organization: Ripco Internet BBS Chicago
x-ident-sender: mambuhl
newsgroups: gnu.gcc.help