Hi Folks!
The following comparision between a const and a Real value does not work as expected:
program Fail2;
const ConstSize = 1.2;
var VarSize: Real = 1.2;
begin if ConstSize <> VarSize then begin WriteLn (ConstSize - VarSize : 0 : 20); WriteLn ('Fails') end else WriteLn ('Works') end.
Output: ======= 0.00000000000000004445 Fails
Version: ======== Reading specs from /usr/local/bin/../lib/gcc-lib/i686-pc-linux-gnu/2.95.2/specs gpc version 20021111, based on gcc-2.95.2 19991024 (release)
Eike
Eike Lange wrote:
The following comparision between a const and a Real value does not work as expected:
program Fail2;
const ConstSize = 1.2;
var VarSize: Real = 1.2;
begin if ConstSize <> VarSize then begin WriteLn (ConstSize - VarSize : 0 : 20); WriteLn ('Fails') end else WriteLn ('Works') end.
Try:
VarSize: LongReal = 1.2;
or:
ConstSize = Real (1.2);
Constants without type specified are represented in the highest available precision (i.e., LongReal). So in the comparison, the Real variable is converted to LongReal again, but some precision has been lost. Therefore the numbers are not equal. That's a general issue with floating point numbers. The GCC info even says:
: `-Wfloat-equal' : Warn if floating point values are used in equality comparisons. : : The idea behind this is that sometimes it is convenient (for the : programmer) to consider floating-point values as approximations to : infinitely precise real numbers. If you are doing this, then you : need to compute (by analysing the code, or in some other way) the : maximum or likely maximum error that the computation introduces, : and allow for it when performing comparisons (and when producing : output, but that's a different problem). In particular, instead : of testing for equality, you would check to see whether the two : values have ranges that overlap; and this is done with the : relational operators, so equality comparisons are probably : mistaken.
(The next version of GPC will support this option, too.)
Frank
Hi!
On Mon, Nov 18, 2002 at 11:10:28AM +0100, Frank Heckenbach wrote:
: `-Wfloat-equal'
[...]
(The next version of GPC will support this option, too.)
Is it then supported with -Wall or -W or do I have to set this explicitly in my makefiles?
Eike
Eike Lange wrote:
On Mon, Nov 18, 2002 at 11:10:28AM +0100, Frank Heckenbach wrote:
: `-Wfloat-equal'
[...]
(The next version of GPC will support this option, too.)
Is it then supported with -Wall or -W or do I have to set this explicitly in my makefiles?
GCC doesn't include it in `-Wall' and `-W', so I think to avoid confusion we shouldn't do it either, so you'll have to set it explicitly.
Frank