Skip to content

Instantly share code, notes, and snippets.

@EdThePro101
Created January 6, 2021 12:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EdThePro101/1394ce3f2eb665e59519854f032def11 to your computer and use it in GitHub Desktop.
Save EdThePro101/1394ce3f2eb665e59519854f032def11 to your computer and use it in GitHub Desktop.
Remap a number from one range to another range. For example, remap celsius to fahrenheit or remap kilometres to miles.
// To remap a value x in range [a, b] to [c, d], we can use:
//
// y = (x - a) * ((d - c) / (b - a)) + c
//
function remapper(x, a, b, c, d) {
let y = (x - a) * ((d - c) / (b - a)) + c;
return y;
}
// Examples:
function celsiusToFahrenheit(celsius) {
return remapper(celsius, 0, 100, 32, 212);
}
// In C, C++ or Java:
// double remapper(double x, double a, double b, double c, double d) {
// double y = (x - a) * ((d - c) / (b - a)) + c;
// return y;
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment