diff --git a/utils.go b/utils.go index d5830a46..46d5909b 100644 --- a/utils.go +++ b/utils.go @@ -57,6 +57,11 @@ func ToScale(input, min, max float64) float64 { } } +// Rescale performs a direct linear rescaling of a number from one scale to another. +func Rescale(input, fromMin, fromMax, toMin, toMax float64) float64 { + return (input-fromMin)*(toMax-toMin)/(fromMax-fromMin) + toMin +} + // DefaultName returns a sensible random default name // for a robot, adaptor or driver func DefaultName(name string) string { diff --git a/utils_test.go b/utils_test.go index 33e22b3d..6f58cb5b 100644 --- a/utils_test.go +++ b/utils_test.go @@ -73,6 +73,11 @@ func TestToScale(t *testing.T) { gobottest.Assert(t, ToScale(0.5, 0, 10), 5.0) } +func TestRescale(t *testing.T) { + gobottest.Assert(t, Rescale(500, 0, 1000, 0, 10), 5.0) + gobottest.Assert(t, Rescale(-1.0, -1, 0, 490, 350), 490.0) +} + func TestRand(t *testing.T) { a := Rand(10000) b := Rand(10000)