From 355181843fa7dd60333c81731695d593ce249623 Mon Sep 17 00:00:00 2001 From: Ron Evans Date: Wed, 15 Aug 2018 17:06:52 +0200 Subject: [PATCH] core: add Rescale utility function for straight linear rescaling Signed-off-by: Ron Evans --- utils.go | 5 +++++ utils_test.go | 5 +++++ 2 files changed, 10 insertions(+) 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)