Skip to content

Commit 2c73cb1

Browse files
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. Fixes #76821
1 parent 1b291b7 commit 2c73cb1

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-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: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -744,3 +744,51 @@ func TestDenomRace(t *testing.T) {
744744
<-c
745745
}
746746
}
747+
748+
func TestRatFloor(t *testing.T) {
749+
var tests = []struct {
750+
rat string
751+
out int64
752+
}{
753+
{"123456.78", 123456},
754+
{"100.5", 100},
755+
{"5645.0222", 5645},
756+
{"89898989", 89898989},
757+
{"0", 0},
758+
{"-123456.78", -123457},
759+
{"-100.5", -101},
760+
{"-5645.0222", -5646},
761+
{"-89898989", -89898989},
762+
}
763+
for i, test := range tests {
764+
x, _ := new(Rat).SetString(test.rat)
765+
out := x.Floor()
766+
if out.Cmp(NewInt(test.out)) != 0 {
767+
t.Errorf("#%d got out = %v; want %v", i, out, test.out)
768+
}
769+
}
770+
}
771+
772+
func TestRatCeil(t *testing.T) {
773+
var tests = []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+
for i, test := range tests {
788+
x, _ := new(Rat).SetString(test.rat)
789+
out := x.Ceil()
790+
if out.Cmp(NewInt(test.out)) != 0 {
791+
t.Errorf("#%d got out = %v; want %v", i, out, test.out)
792+
}
793+
}
794+
}

0 commit comments

Comments
 (0)