Difference between revisions of "Floating Point Gotchas"

From D Wiki
Jump to: navigation, search
m (fix formatting)
m (Correct reference links)
 
(One intermediate revision by one other user not shown)
Line 1: Line 1:
see forum discussion here: http://forum.dlang.org/post/oxadmevgkefklttnbbpi@forum.dlang.org
+
Floating point comparisons should be undertaken with care, because decimal numbers cannot be exactly represented using float or double.
  
Floating point comparisons should be undertaken with care, because decimal numbers cannot be exactly represented using float or double.  The classic reference on
+
One should therefore in most cases use [https://dlang.org/phobos/std_math_operations.html#.feqrel std.math.feqrel] and  or [https://dlang.org/phobos/std_math_operations.html#.approxEqual std.math.approxEqual] instead of checking for simple equality.
this topic is here:
 
 
 
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
 
 
 
 
 
One should therefore in most cases use [http://dlang.org/library/std/math/feqrel.html std.math.feqrel] and  or [http://dlang.org/phobos/std_math.html#.approxEqual std.math.approxEqual] instead of checking for simple equality.
 
  
 
These functions may be passed as a predicate to the std.algorithm library in Phobos when for example doing a search for a specific floating point value:
 
These functions may be passed as a predicate to the std.algorithm library in Phobos when for example doing a search for a specific floating point value:
 
  
 
     void main() @safe {
 
     void main() @safe {
Line 26: Line 19:
 
         r.canFind!q{ feqrel(cast()a, cast()b) >= 21 }(item).writeln;
 
         r.canFind!q{ feqrel(cast()a, cast()b) >= 21 }(item).writeln;
 
     }
 
     }
 +
 +
== See also ==
 +
* [http://forum.dlang.org/post/oxadmevgkefklttnbbpi@forum.dlang.org Forum discussion]
 +
* [http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html Classic reference on this topic]
 +
 +
[[Category:Tutorials]]

Latest revision as of 00:49, 23 September 2022

Floating point comparisons should be undertaken with care, because decimal numbers cannot be exactly represented using float or double.

One should therefore in most cases use std.math.feqrel and or std.math.approxEqual instead of checking for simple equality.

These functions may be passed as a predicate to the std.algorithm library in Phobos when for example doing a search for a specific floating point value:

   void main() @safe {
       import std.stdio, std.range, std.algorithm, std.math;
   
       immutable float oneDegree = (PI / 180.0f);
       immutable float first = -(oneDegree * 10.0f);
       immutable float second = (oneDegree * 10.0f);
       immutable float step = 0.000001f;
       immutable float[] r = iota(first, second, step).array;
   
       //r.writeln;
   
       immutable float item = 0.174531f;
       r.canFind!q{ feqrel(cast()a, cast()b) >= 21 }(item).writeln;
   }

See also