[fpc-pascal] Floating point question
Michael Van Canneyt
michael at freepascal.org
Sat Feb 17 14:38:22 CET 2024
On Sat, 17 Feb 2024, wkitty42--- via fpc-pascal wrote:
> On 2/16/24 9:57 AM, James Richters via fpc-pascal wrote:
>>> So you are saying when constant propagation is on, an expression should
>>> have a different result than with constant propagation off?
>>
>> The result of math when using constants MUST be the same as the result of
>> identical math using variables.
As far as I can see, in that case you must simply type your constants.
Variables are always typed - their precision is determined by the type you
have specified.
For constants, the compiler will choose a type and consequently the precision.
Jonas and others have explained the rules that the compiler uses.
If you don't like the rules that the compiler uses, you can set a type for your
constants. When you explicitly set a type, you are also specifying the precision of the calculation.
And if you have set the precision, then the calculation will be identical to the
calculation when you use a variable of the same type (if not, it's indeed a bug).
There are 2 ways to do so:
Const
MyConst : Double = 1.23e45;
or
Const
MyConst = Double(1.23e45);
The latter can also be used in an expression
X := Y * Double(1.23e45);
There can be discussion about the rules that the compiler uses when it chooses a type,
but any given set of rules will always have consequences that may or may not be desirable.
Possibly some compiler switches can be invented that modify the compiler's
rules for the constant type to use.
(incidentally, this is one of the reasons the FPC team does not want to make
inline variables as Delphi does, since there the type will again be determined by
the compiler - just as for constants, leading to ambiguity...)
Michael.
More information about the fpc-pascal
mailing list