Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle NaNs when comparing BigFloat against Float #13294

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions spec/std/big/big_float_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,22 @@ describe "BigFloat" do
end
end

describe "#<=>" do
it "compares against NaNs" do
(1.to_big_f <=> Float64::NAN).should be_nil
(1.to_big_f <=> Float32::NAN).should be_nil
(Float64::NAN <=> 1.to_big_f).should be_nil
(Float32::NAN <=> 1.to_big_f).should be_nil

typeof(1.to_big_f <=> Float64::NAN).should eq(Int32?)
typeof(1.to_big_f <=> Float32::NAN).should eq(Int32?)
typeof(Float64::NAN <=> 1.to_big_f).should eq(Int32?)
typeof(Float32::NAN <=> 1.to_big_f).should eq(Int32?)

typeof(1.to_big_f <=> 1.to_big_f).should eq(Int32)
end
end

describe "unary #-" do
it do
bf = "0.12345".to_big_f
Expand Down
21 changes: 15 additions & 6 deletions src/big/big_float.cr
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,8 @@ struct BigFloat < Float
LibGMP.mpf_cmp_z(self, other)
end

def <=>(other : Float32 | Float64)
LibGMP.mpf_cmp_d(self, other.to_f64)
def <=>(other : Float::Primitive)
LibGMP.mpf_cmp_d(self, other) unless other.nan?
end

def <=>(other : Number)
Expand Down Expand Up @@ -387,10 +387,6 @@ end
struct Number
include Comparable(BigFloat)

def <=>(other : BigFloat)
-(other <=> self)
end

def +(other : BigFloat)
other + self
end
Expand All @@ -412,6 +408,19 @@ struct Number
end
end

struct Int
def <=>(other : BigFloat)
-(other <=> self)
end
end

struct Float
def <=>(other : BigFloat)
cmp = other <=> self
-cmp if cmp
end
end

class String
# Converts `self` to a `BigFloat`.
#
Expand Down