-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimplesolver.go
44 lines (33 loc) · 1.08 KB
/
simplesolver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package equation
import (
"errors"
"math"
)
type simpleSolver struct{}
// Solve the specified equation and sets the coifficients and the constant
func (s simpleSolver) Solve(equation []Equation) (Solution, error) {
if len(equation) != 2 {
return Solution{0, 0}, errors.New("two equations are required")
}
e1 := equation[0]
e2 := equation[1]
if almostEqual(e1.FirstCoefiicient*e2.SecondCoefiicient, e1.SecondCoefiicient*e2.FirstCoefiicient) {
return Solution{0, 0}, errors.New("the equation system doesn't have a determinstic output")
}
denomirator := (e1.FirstCoefiicient*e2.SecondCoefiicient - e1.SecondCoefiicient*e2.FirstCoefiicient)
x := (e1.EquationConstant*e2.SecondCoefiicient - e1.SecondCoefiicient*e2.EquationConstant) / denomirator
y := (e1.FirstCoefiicient*e2.EquationConstant - e1.EquationConstant*e2.FirstCoefiicient) / denomirator
var sol = &Solution{x, y}
return *sol, nil
}
func almostEqual(a float64, b float64) bool {
if a == b {
return true
}
absDiff := math.Abs(a - b)
epsilon := .000000001
if absDiff < epsilon {
return true
}
return false
}