gap-system / gap

Main development repository for GAP - Groups, Algorithms, Programming, a System for Computational Discrete Algebra
https://www.gap-system.org
GNU General Public License v2.0
800 stars 163 forks source link

Several default methods for floats are wrong #1988

Open fingolfin opened 6 years ago

fingolfin commented 6 years ago

Several default methods for floats in the GAP library are wrong, and can e.g. lead to mathematically inconsistent implementations of floateans. Possible actions include:

Here are some of the functions I consider wrong:

InstallMethod( AbsoluteValue, "for floats", [ IsFloat ], -1,
        function ( x )
    if x < Zero(x) then return -x; else return x; fi;
end );

InstallMethod( Norm, "for floats", [ IsFloat ], -1,
        function ( x )
    return x*x;
end );

InstallMethod( Argument, "for floats", [ IsFloat ], -1,
        function ( x )
    return Zero(x);
end );

These are wrong if x is a complex float. Since there doesn't seem a way to distinguish complex floats from real ones (e.g. no filter for that, as far as I can tell), this can easily lead to mathematically inconsistent implementations of floateans.

InstallMethod( SignFloat, "for floats", [ IsFloat ], -1,
        function ( x )
    if x < Zero(x) then return -1; elif IsZero(x) then return 0; else return 1; fi;
end );

This leads to incorrect results:

gap> SignFloat(-0.0);
0
gap> nan:=0.0/0.0;
nan
gap> SignFloat(nan);
1

For several operations, I also wonder whether it is wise to provide numerically bad default implementations. E.g. rounding is a very sensitive thing, and while e.g. Floor(x+MakeFloat(x,1/2)) as default for Round may seem compelling at a first glance, it gives incorrect results for a large number of floats. Example:

gap> a:=2^52+1;; x:=a*1.;; Int(x) = a; y:=Floor(x+MakeFloat(x,1/2));; x=y;
true
false
gap> x-y;
-1.

So an exact integral float is rounded incorrectly. There are more problems, for details see e.g. http://blog.frama-c.com/index.php?post/2013/05/02/nearbyintf1

A more extensive test suite would be helpful in all this, too.

laurentbartholdi commented 6 years ago

Dear @Max: I agree with you that this could be done better. The idea was to have at least something, but of course it must not give wrong results. There are different issues, as you sorted them out:

fingolfin commented 6 years ago