Skip to content

Instantly share code, notes, and snippets.

@ufuk
Created July 25, 2017 10:51
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 ufuk/a13c9771e567ac2f4d95abf90867d261 to your computer and use it in GitHub Desktop.
Save ufuk/a13c9771e567ac2f4d95abf90867d261 to your computer and use it in GitHub Desktop.
Scales and translates a value (x) into a new range [a, b].
/**
* Scales and translates a value (x) into a new range [a, b].
*
* Formula:
* f(x) = a + (b - a)(x - min)/(max - min)
*
* See also: https://stackoverflow.com/a/5295202
*/
public BigDecimal scaleAndTranslateIntoRange(BigDecimal value, BigDecimal actualMin, BigDecimal actualMax, BigDecimal desiredMin, BigDecimal desiredMax) {
return desiredMax.subtract(desiredMin).multiply(value.subtract(actualMin))
.divide(actualMax.subtract(actualMin), RoundingMode.HALF_UP)
.add(desiredMin)
.setScale(2, RoundingMode.HALF_UP);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment