Skip to content

Commit bc8315f

Browse files
authored
Added Pythagoras Theorem (#205)
* Added Pythagoras Theorem * Removed Main, changed package name * Exported Vector Struct for external use * TableDriven Test, better float64 handling * Parallel Testing, fixed leftover math.Abs function
1 parent e43e532 commit bc8315f

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

math/pythagoras/pythagoras.go

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
package pythagoras
2+
3+
import (
4+
"math"
5+
)
6+
7+
//Vector defines a tuple with 3 values in 3d-space
8+
type Vector struct {
9+
x float64
10+
y float64
11+
z float64
12+
}
13+
14+
//Distance calculates the distance between to vectors with the Pythagoras theorem
15+
func Distance(a, b Vector) float64 {
16+
res := math.Pow(b.x-a.x, 2.0) + math.Pow(b.y-a.y, 2.0) + math.Pow(b.z-a.z, 2.0)
17+
return math.Sqrt(res)
18+
}

math/pythagoras/pythagoras_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package pythagoras
2+
3+
import (
4+
"math"
5+
"testing"
6+
)
7+
8+
// TableDrivenTest for checking multiple values against our Test Function
9+
var distanceTest = []struct {
10+
name string
11+
v1 Vector
12+
v2 Vector
13+
res float64
14+
}{
15+
{"random negative vector", Vector{2, -1, 7}, Vector{1, -3, 5}, 3.0},
16+
{"random wide vectors", Vector{4, 10, 9}, Vector{4, 3, 5}, 8.06},
17+
{"random wide vectors", Vector{8, 5, 5}, Vector{1, 1, 12}, 10.67},
18+
{"random short vectors", Vector{1, 1, 1}, Vector{2, 2, 2}, 1.73},
19+
}
20+
21+
//TestDistance tests the Function Distance with 2 vectors
22+
func TestDistance(t *testing.T) {
23+
t.Parallel() // marks TestDistance as capable of running in parallel with other tests
24+
for _, tt := range distanceTest {
25+
tt := tt // NOTE: https://github.com/golang/go/wiki/CommonMistakes#using-goroutines-on-loop-iterator-variables
26+
t.Run(tt.name, func(t *testing.T) {
27+
t.Parallel()
28+
res := Distance(tt.v1, tt.v2) // Calculate result for
29+
roundRes := (math.Floor(res*100) / 100) // Round to 2 decimal places because we can't compare an infinite number of places
30+
// Check result
31+
if roundRes != tt.res {
32+
t.Errorf("Distance(%v, %v) = %f, expected %f",
33+
tt.v1, tt.v2, roundRes, tt.res)
34+
}
35+
})
36+
}
37+
}

0 commit comments

Comments
 (0)