Skip to content

Commit

Permalink
FloorDiv bug fix, Example (and regression test)
Browse files Browse the repository at this point in the history
  • Loading branch information
skeys committed May 12, 2016
1 parent 8b69f65 commit 55ff14d
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 8 deletions.
18 changes: 10 additions & 8 deletions base/math.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,23 +44,25 @@ func Horner(x float64, c ...float64) float64 {
// It uses integer math only, so is more efficient than using floating point
// intermediate values. This function can be used in many places where INT()
// appears in AA. As with built in integer division, it panics with y == 0.
func FloorDiv(x, y int) int {
if (x < 0) == (y < 0) {
return x / y
func FloorDiv(x, y int) (q int) {
q = x / y
if (x < 0) != (y < 0) && x%y != 0 {
q--
}
return x/y - 1
return
}

// FloorDiv64 returns the integer floor of the fractional value (x / y).
//
// It uses integer math only, so is more efficient than using floating point
// intermediate values. This function can be used in many places where INT()
// appears in AA. As with built in integer division, it panics with y == 0.
func FloorDiv64(x, y int64) int64 {
if (x < 0) == (y < 0) {
return x / y
func FloorDiv64(x, y int64) (q int64) {
q = x / y
if (x < 0) != (y < 0) && x%y != 0 {
q--
}
return x/y - 1
return
}

// Cmp compares two float64s and returns -1, 0, or 1 if a is <, ==, or > b,
Expand Down
50 changes: 50 additions & 0 deletions base/math_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,56 @@ import (
"github.com/soniakeys/meeus/base"
)

func ExampleFloorDiv() {
// compare to / operator examples in Go spec at
// https://golang.org/ref/spec#Arithmetic_operators
fmt.Println(base.FloorDiv(+5, +3))
fmt.Println(base.FloorDiv(-5, +3))
fmt.Println(base.FloorDiv(+5, -3))
fmt.Println(base.FloorDiv(-5, -3))
fmt.Println()
// exact divisors, no remainders
fmt.Println(base.FloorDiv(+6, +3))
fmt.Println(base.FloorDiv(-6, +3))
fmt.Println(base.FloorDiv(+6, -3))
fmt.Println(base.FloorDiv(-6, -3))
// Output:
// 1
// -2
// -2
// 1
//
// 2
// -2
// -2
// 2
}

func ExampleFloorDiv64() {
// compare to / operator examples in Go spec at
// https://golang.org/ref/spec#Arithmetic_operators
fmt.Println(base.FloorDiv64(+5, +3))
fmt.Println(base.FloorDiv64(-5, +3))
fmt.Println(base.FloorDiv64(+5, -3))
fmt.Println(base.FloorDiv64(-5, -3))
fmt.Println()
// exact divisors, no remainders
fmt.Println(base.FloorDiv64(+6, +3))
fmt.Println(base.FloorDiv64(-6, +3))
fmt.Println(base.FloorDiv64(+6, -3))
fmt.Println(base.FloorDiv64(-6, -3))
// Output:
// 1
// -2
// -2
// 1
//
// 2
// -2
// -2
// 2
}

// Section "Trigonometric functions of large angles":
//
// Meeus makes his point, but an example with integer values is a bit unfair
Expand Down

0 comments on commit 55ff14d

Please sign in to comment.