mirror of
https://github.com/lukewilson2002/autotrader.git
synced 2025-08-02 21:19:33 +00:00
Added Round function and unit tests
This commit is contained in:
25
utils.go
25
utils.go
@@ -1,13 +1,14 @@
|
||||
package autotrader
|
||||
|
||||
import (
|
||||
"math"
|
||||
"os/exec"
|
||||
"runtime"
|
||||
|
||||
"golang.org/x/exp/constraints"
|
||||
)
|
||||
|
||||
const floatComparisonTolerance = float64(1e-6)
|
||||
const float64Tolerance = float64(1e-6)
|
||||
|
||||
// Crossover returns true if the latest a value crosses above the latest b value, but only if it just happened. For example, if a series is [1, 2, 3, 4, 5] and b series is [1, 2, 3, 4, 3], then Crossover(a, b) returns false because the latest a value is 5 and the latest b value is 3. However, if a series is [1, 2, 3, 4, 5] and b series is [1, 2, 3, 4, 6], then Crossover(a, b) returns true because the latest a value is 5 and the latest b value is 6
|
||||
func Crossover(a, b Series) bool {
|
||||
@@ -22,8 +23,28 @@ func EasyIndex(i, n int) int {
|
||||
return i
|
||||
}
|
||||
|
||||
// EqualApprox returns true if a and b are approximately equal. NaN and Inf are handled correctly. The tolerance is 1e-6 or 0.0000001.
|
||||
func EqualApprox(a, b float64) bool {
|
||||
return Abs(a-b) < floatComparisonTolerance
|
||||
if math.IsNaN(a) || math.IsNaN(b) {
|
||||
return math.IsNaN(a) && math.IsNaN(b)
|
||||
} else if math.IsInf(a, 1) || math.IsInf(b, 1) {
|
||||
return math.IsInf(a, 1) && math.IsInf(b, 1)
|
||||
} else if math.IsInf(a, -1) || math.IsInf(b, -1) {
|
||||
return math.IsInf(a, -1) && math.IsInf(b, -1)
|
||||
}
|
||||
return math.Abs(a-b) <= float64Tolerance
|
||||
}
|
||||
|
||||
// Round returns f rounded to d decimal places. d may be negative to round to the left of the decimal point.
|
||||
//
|
||||
// Examples:
|
||||
//
|
||||
// Round(123.456, 0) // 123.0
|
||||
// Round(123.456, 1) // 123.5
|
||||
// Round(123.456, -1) // 120.0
|
||||
func Round(f float64, d int) float64 {
|
||||
ratio := math.Pow10(d)
|
||||
return math.Round(f*ratio) / ratio
|
||||
}
|
||||
|
||||
func Abs[T constraints.Integer | constraints.Float](a T) T {
|
||||
|
Reference in New Issue
Block a user