[fpc-pascal] Order of Precedence: FPC/Delphi vs Java

Santiago A. svaa at ciberpiula.net
Wed Oct 3 21:05:33 CEST 2018


El 03/10/18 a las 10:40, mailinglists at geldenhuys.co.uk escribió:
> I have this simple little test. My expected answer for all the 
> calculations are 0 (zero), but both FPC and Delphi give different 
> results. Java is the only one that seems consistent regarding the 
> results.
>
> Can anybody explain this, especially the first 3 very small negative 
> numbers that Delphi and FPC produces? I know  not all floating point 
> values can be stored exactly (or something like that), and when doing 
> calculations, it might do a auto data type conversion. But is any of 
> that taking place here?

I don't know why you want to compare two floats, but you'd better use 
currency type. Float is for calculus, but comparing float1=float2 (or 
float1>float2) is rolling the dice. Obviously, the more precision, the 
less errors. But an accurate, intuitive result, is not guaranteed.

People who play with maths may use something like
function equal(const f1,f2:Extended; const Error:extended=1E-6):boolean;
begin
  Result:=(abs(f1-f2)<error);
end;

But for most applications,  using a function like "equal" (and "less", 
"lessOrEq" etc) everywhere is a burden that makes not sense. I think 
that every programing language should include a fixed precision type.  
Freepascal has at least currency, that is four decimals, use it.

What does java does? I don't know. Perhaps it just rounds the output, 
try  System.out.println(ans==0.0). Perhaps it uses a high precision that 
*in this case* gets always 0.

But the question is that floating point representation can't store 
accurately many numbers. To begin with,  0.1 in base 10, is periodic 
number in binary 0.0001...001..001... so it has to truncate it, and when 
you truncate, the result depends of the order of operations, no matter 
the language or precision. So, it is matter of probability to get 1.0000 
or 1.0001 or 0.9999, if you expect 1, psychologically 1.0001 looks 
better result than 0.9999. Dephi or Freepascal are doing nothing wrong.

-- 
Saludos

Santiago A.



More information about the fpc-pascal mailing list