[fpc-devel] Floating point precision

Jonas Maebe jonas.maebe at elis.ugent.be
Tue Apr 10 09:04:06 CEST 2007


On 09 Apr 2007, at 22:38, Colin Western wrote:

> Jonas Maebe wrote:
>> On 06 Apr 2007, at 21:36, Colin Western wrote:
>>> Can I ask what determines the precision of floating point  
>>> calculations are done in? It seems that fpc treats (for example,  
>>> with J declared as integer)
>>>
>>> 1/sqrt(J+1.0) as single
>>>
>>> but
>>>
>>> 1/sqrt(J+1) as double
>> In 2.1.2 and 2.2, both will be evaluated as single (except on  
>> 80x87, because it is not possible to tell the 80x87 to perform a  
>> particular calculation using only single/double precision).
>
> The current SVN (which is the only one I am using at the moment)  
> does give the results at different precisions as shown for x86_64  
> and PPC - I don't know if that should be considered as a bug.

Ah, yes: the j+1 is evaluated (obviously) as integer, and then it's  
the overloading mechanism that jumps in to decide whether sqrt 
(single) or sqrt(double) should be picked. I guess that one simply  
picks the one with the most precision if there is no exact match and  
you pass an integer argument.

In case of j+1.0, 1.0 is a single, so j+1.0 also becomes a single and  
since there is an sqrt(single), the exact match is picked instead.

> (I understand that the older 386 architecture will normally use  
> double or extended all the time).

Indeed.

> Having said that, for numerical programming if double is wanted,  
> the evaluation as double in the absence of specific precision  
> information is actually desirable, and avoids some hard to find  
> errors. Values like Sqrt(2) are common, which I should presumably  
> write as Sqrt(Double(2)) to be sure I don't loose precision. It  
> came up because my application (which requires double rather than  
> single accuracy) was giving slightly different results for  
> different architectures. I have now gone through and fixed the  
> differences I can find, and the results are now the same, but it is  
> difficult to be sure I have caught all the problem areas.
>
> Is there some way of optionally making double the default for  
> constants (rather than single) as a way of avoiding these errors?

Please file a bug report/feature request for this. The current  
behaviour is needed for Delphi compatibility, and for avoiding wrong  
precision loss warnings like in
   http://www.freepascal.org/mantis/view.php?id=7179


Jonas



More information about the fpc-devel mailing list