Skip to content
Open
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
15 changes: 15 additions & 0 deletions src/math/big/rat.go
Original file line number Diff line number Diff line change
Expand Up @@ -559,3 +559,18 @@ func (z *Rat) Quo(x, y *Rat) *Rat {
z.a.neg = a.neg != b.neg
return z.norm()
}

// Floor returns the largest [Int] <= z.
func (z *Rat) Floor() *Int {
// z.b is positive, so Euclidean division == floor division
return new(Int).Div(&z.a, &z.b)
}

// Ceil returns the smallest [Int] >= z.
func (z *Rat) Ceil() *Int {
if z.IsInt() {
return new(Int).Set(&z.a)
}
f := z.Floor()
return f.Add(f, intOne)
}
48 changes: 48 additions & 0 deletions src/math/big/rat_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -744,3 +744,51 @@ func TestDenomRace(t *testing.T) {
<-c
}
}

func TestRatFloor(t *testing.T) {
var tests = []struct {
rat string
out int64
}{
{"123456.78", 123456},
{"100.5", 100},
{"5645.0222", 5645},
{"89898989", 89898989},
{"0", 0},
{"-123456.78", -123457},
{"-100.5", -101},
{"-5645.0222", -5646},
{"-89898989", -89898989},
}
for i, test := range tests {
x, _ := new(Rat).SetString(test.rat)
out := x.Floor()
if out.Cmp(NewInt(test.out)) != 0 {
t.Errorf("#%d got out = %v; want %v", i, out, test.out)
}
}
}

func TestRatCeil(t *testing.T) {
var tests = []struct {
rat string
out int64
}{
{"123456.78", 123457},
{"100.5", 101},
{"5645.0222", 5646},
{"89898989", 89898989},
{"0", 0},
{"-123456.78", -123456},
{"-100.5", -100},
{"-5645.0222", -5645},
{"-89898989", -89898989},
}
for i, test := range tests {
x, _ := new(Rat).SetString(test.rat)
out := x.Ceil()
if out.Cmp(NewInt(test.out)) != 0 {
t.Errorf("#%d got out = %v; want %v", i, out, test.out)
}
}
}