Skip to content

Commit

Permalink
Do not overflow when converting large rationals to float
Browse files Browse the repository at this point in the history
  • Loading branch information
fingolfin committed Oct 18, 2020
1 parent e62d395 commit 7d8f948
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
2 changes: 1 addition & 1 deletion doc/ref/floats.xml
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ or floating-point numbers. Floating-point numbers may
also be created, in any floating-point representation, using
<Ref Constr="NewFloat"/> as in <C>NewFloat(IsIEEE754FloatRep,355/113)</C>,
by supplying the category filter of the desired new floating-point number;
or using <Ref Oper="MakeFloat"/> as in <C>NewFloat(1.0,355/113)</C>,
or using <Ref Oper="MakeFloat"/> as in <C>MakeFloat(1.0,355/113)</C>,
by supplying a sample floating-point number.
<P/>

Expand Down
10 changes: 8 additions & 2 deletions lib/float.gi
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,10 @@ BindGlobal("INSTALLFLOATCONSTRUCTORS", function(arg)
fi;

InstallMethod(NewFloat, [filter,IsRat], -1, function(filter,obj)
return NewFloat(filter,NumeratorRat(obj))/NewFloat(filter,DenominatorRat(obj));
local num, den;
num := NumeratorRat(obj);
den := DenominatorRat(obj);
return NewFloat(filter, QuoInt(num, den)) + NewFloat(filter, RemInt(num, den)) / NewFloat(filter, den);
end);

InstallMethod(NewFloat, [filter,IsInfinity], -1, function(filter,obj)
Expand Down Expand Up @@ -138,7 +141,10 @@ BindGlobal("INSTALLFLOATCONSTRUCTORS", function(arg)
end);

InstallMethod(MakeFloat, [filter,IsRat], -1, function(filter,obj)
return MakeFloat(filter,NumeratorRat(obj))/MakeFloat(filter,DenominatorRat(obj));
local num, den;
num := NumeratorRat(obj);
den := DenominatorRat(obj);
return MakeFloat(filter, QuoInt(num, den)) + MakeFloat(filter, RemInt(num, den)) / MakeFloat(filter, den);
end);

InstallMethod(MakeFloat, [filter,IsInfinity], -1, function(filter,obj)
Expand Down
32 changes: 31 additions & 1 deletion tst/testinstall/float.tst
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#@local neginf,posinf,r,nan,l,f,g
#@local neginf,posinf,r,nan,l,f,g,a,b
gap> START_TEST("float.tst");

# make sure we are testing the built-in machine floats
Expand Down Expand Up @@ -32,6 +32,36 @@ inf
gap> Float(-infinity);
-inf

#
gap> r := (10^309 + 1) / 10^308;;
gap> Float(r);
10.
gap> Float(-r);
-10.
gap> NewFloat(IsIEEE754FloatRep, r);
10.
gap> NewFloat(IsIEEE754FloatRep, -r);
-10.
gap> MakeFloat(0.0, r);
10.
gap> MakeFloat(0.0, -r);
-10.

#
gap> r := (10^309-1) / 10^308;;
gap> Float(r);
10.
gap> Float(-r);
-10.
gap> NewFloat(IsIEEE754FloatRep, r);
10.
gap> NewFloat(IsIEEE754FloatRep, -r);
-10.
gap> MakeFloat(0.0, r);
10.
gap> MakeFloat(0.0, -r);
-10.

#
# input floats directly
#
Expand Down

0 comments on commit 7d8f948

Please sign in to comment.