Add Clamp

This commit is contained in:
bloeys
2024-05-14 06:06:00 +04:00
parent b9faa2e59e
commit 6adefa81f7
5 changed files with 94 additions and 2 deletions

View File

@ -20,6 +20,8 @@ gglm currently has the following:
## Installation
Note: gglm requires Go 1.18 or higher.
`go get github.com/bloeys/gglm`
## Usage

View File

@ -1,6 +1,10 @@
package gglm
import "math"
import (
"math"
"golang.org/x/exp/constraints"
)
// EqF32 true if abs(f1-f2) <= F32Epsilon
func EqF32(f1, f2 float32) bool {
@ -52,3 +56,21 @@ func Abs32(x float32) float32 {
func Sqrt32(x float32) float32 {
return float32(math.Sqrt(float64(x)))
}
// Clamp returns:
//
// min if x<min
// max if x>max
// x if x>=min && x<=max
func Clamp[T constraints.Ordered](x, min, max T) T {
if x < min {
return min
}
if x > max {
return max
}
return x
}

64
gglm/scalar_test.go Executable file
View File

@ -0,0 +1,64 @@
package gglm_test
import (
"testing"
"github.com/bloeys/gglm/gglm"
)
func TestClamp(t *testing.T) {
x := 5
ans := 5
if gglm.Clamp(x, 0, 10) != ans {
t.Errorf("Got: %v; Expected: %v", x, ans)
}
x = 10
ans = 10
if gglm.Clamp(x, 0, 10) != ans {
t.Errorf("Got: %v; Expected: %v", x, ans)
}
x = 20
ans = 10
if gglm.Clamp(x, 0, 10) != ans {
t.Errorf("Got: %v; Expected: %v", x, ans)
}
x = -10
ans = 0
if gglm.Clamp(x, 0, 10) != ans {
t.Errorf("Got: %v; Expected: %v", x, ans)
}
xf := 1.5
ansf := 1.5
if gglm.Clamp(xf, 0, 10) != ansf {
t.Errorf("Got: %v; Expected: %v", xf, ansf)
}
xf = 15
ansf = 10
if gglm.Clamp(xf, 0, 10) != ansf {
t.Errorf("Got: %v; Expected: %v", xf, ansf)
}
xf = -1.5
ansf = 0
if gglm.Clamp(xf, 0, 10) != ansf {
t.Errorf("Got: %v; Expected: %v", xf, ansf)
}
xf = 2
ansf = 1.5
if gglm.Clamp(xf, 0.5, 1.5) != ansf {
t.Errorf("Got: %v; Expected: %v", xf, ansf)
}
xf = 1.2
ansf = 1.2
if gglm.Clamp(xf, 0.5, 1.5) != ansf {
t.Errorf("Got: %v; Expected: %v", xf, ansf)
}
}

4
go.mod
View File

@ -1,3 +1,5 @@
module github.com/bloeys/gglm
go 1.17
go 1.18
require golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842

2
go.sum
View File

@ -0,0 +1,2 @@
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842 h1:vr/HnozRka3pE4EsMEg1lgkXJkTFJCVUX+S/ZT6wYzM=
golang.org/x/exp v0.0.0-20240506185415-9bf2ced13842/go.mod h1:XtvwrStGgqGPLc4cjQfWqZHG1YFdYs6swckp8vpsjnc=