40 lines
597 B
Go
40 lines
597 B
Go
package math
|
|
|
|
import (
|
|
"math"
|
|
)
|
|
|
|
type SignedNumber interface {
|
|
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~float32 | ~float64
|
|
}
|
|
|
|
type Float interface {
|
|
~float32 | ~float64
|
|
}
|
|
|
|
func Abs[T SignedNumber](i T) T {
|
|
var zero T
|
|
if i < zero {
|
|
return -i
|
|
}
|
|
return i
|
|
}
|
|
|
|
func Round[T Float](n T, precision int) T {
|
|
if precision == 0 {
|
|
return T(math.Round(float64(n)))
|
|
}
|
|
|
|
ratio := math.Pow(10, float64(precision))
|
|
f := math.Round(float64(n)*ratio) / ratio
|
|
return T(f)
|
|
}
|
|
|
|
func RoundInt[T Float](n T) int {
|
|
return int(Round(n, 0))
|
|
}
|
|
|
|
func Sqrt[T Float](n T) T {
|
|
return T(math.Sqrt(float64(n)))
|
|
}
|