Reputation: 11389
I'm dealing with the pitch of a joystick.
This pitch can vary between 0 (all down) and 1 (all up). A pitch of 0.5 would mean that the joystick is in its middle position.
I would like to find a formula that would "map" this pitch to a given minimum and maximum.
The formular would tell me
- that a joystick pitch value of 0 would correspond to a given minimum (let's say -20)
- that a joystick pitch value of 1 would correspond to a given maximum (let's say 20)
- that a joystick pitch value of 0.5 would correspond to 0 (as it's in the middle of minimum and maximum
I have a black out, I don't find the formula to solve this riddle.
Thank you for the help.
Upvotes: 0
Views: 2037
Reputation: 13652
That's pretty simple, just take the proportion of the distance between max
and min
and add min
:
public double Range(double val, double min, double max)
=> min + val * (max - min);
Example usage:
Range(0.0, -20, 20)
Range(0.5, -20, 20)
Range(1.0, -20, 20)
Output
-20
0
20
Upvotes: 2
Reputation: 45736
This is normally known as the "map range" equation/function. Many graphics libraries come with this as a standard part of the library because of how commonly it's used.
Rosetta Code has implementations in every major language.
The implementation and example for C# is:
using System;
using System.Linq;
public class MapRange
{
public static void Main() {
foreach (int i in Enumerable.Range(0, 11))
Console.WriteLine($"{i} maps to {Map(0, 10, -1, 0, i)}");
}
static double Map(double a1, double a2, double b1, double b2, double s) => b1 + (s - a1) * (b2 - b1) / (a2 - a1);
}
Upvotes: 0
Reputation: 42119
(max - min) * value + min
where value
is in the range [0,1]
should map it to the range [min,max]
. In practice there may be some concerns, depending on the programming language† and values, e.g., if min
and max
are the minimum and maximum of a signed integer type, you cannot compute max - min
without overflow in that same type. Using floating point types for all is probably safest.
† When I answered, the question was not tagged with any language, now it is tagged with C# which I am not particularly fluent in.
Upvotes: 1