Skip to content

Commit 57522f4

Browse files
author
Armin Günther
committed
math/big: add Floor and Ceil methods to Rat
Adds methods for floor and ceil of a rational number r, floor(r) is the largest integer <= r and ceil(r) is the smallest integer >= r.
1 parent 1b291b7 commit 57522f4

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

src/math/big/rat.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -559,3 +559,18 @@ func (z *Rat) Quo(x, y *Rat) *Rat {
559559
z.a.neg = a.neg != b.neg
560560
return z.norm()
561561
}
562+
563+
// Floor returns the largest [Int] <= z.
564+
func (z *Rat) Floor() *Int {
565+
// z.b is positive, so Euclidean division == floor division
566+
return new(Int).Div(&z.a, &z.b)
567+
}
568+
569+
// Ceil returns the smallest [Int] >= z.
570+
func (z *Rat) Ceil() *Int {
571+
if z.IsInt() {
572+
return new(Int).Set(&z.a)
573+
}
574+
f := z.Floor()
575+
return f.Add(f, intOne)
576+
}

src/math/big/rat_test.go

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -744,3 +744,53 @@ func TestDenomRace(t *testing.T) {
744744
<-c
745745
}
746746
}
747+
748+
var ratFloorTests = []struct {
749+
rat string
750+
out int64
751+
}{
752+
{"123456.78", 123456},
753+
{"100.5", 100},
754+
{"5645.0222", 5645},
755+
{"89898989", 89898989},
756+
{"0", 0},
757+
{"-123456.78", -123457},
758+
{"-100.5", -101},
759+
{"-5645.0222", -5646},
760+
{"-89898989", -89898989},
761+
}
762+
763+
func TestRatFloor(t *testing.T) {
764+
for i, test := range ratFloorTests {
765+
x, _ := new(Rat).SetString(test.rat)
766+
out := x.Floor()
767+
if out.Cmp(NewInt(test.out)) != 0 {
768+
t.Errorf("#%d got out = %v; want %v", i, out, test.out)
769+
}
770+
}
771+
}
772+
773+
var ratCeilTests = []struct {
774+
rat string
775+
out int64
776+
}{
777+
{"123456.78", 123457},
778+
{"100.5", 101},
779+
{"5645.0222", 5646},
780+
{"89898989", 89898989},
781+
{"0", 0},
782+
{"-123456.78", -123456},
783+
{"-100.5", -100},
784+
{"-5645.0222", -5645},
785+
{"-89898989", -89898989},
786+
}
787+
788+
func TestRatCeil(t *testing.T) {
789+
for i, test := range ratCeilTests {
790+
x, _ := new(Rat).SetString(test.rat)
791+
out := x.Ceil()
792+
if out.Cmp(NewInt(test.out)) != 0 {
793+
t.Errorf("#%d got out = %v; want %v", i, out, test.out)
794+
}
795+
}
796+
}

0 commit comments

Comments
 (0)