Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Suggestion] Math.lerp and Math.normalize #18

Open
WickyNilliams opened this issue May 20, 2020 · 2 comments
Open

[Suggestion] Math.lerp and Math.normalize #18

WickyNilliams opened this issue May 20, 2020 · 2 comments

Comments

@WickyNilliams
Copy link

WickyNilliams commented May 20, 2020

Linear extrapolation and normalization are very common operations, particularly for graphics programming. I think they would make good candidates for inclusion in the standard.

For context, both of these are essentially specialisations of the proposed Math.scale, where:

  • normalize is equivalent to Math.scale(value, min, max, 0, 1)
  • lerp is equivalent to Math.scale(value, 0, 1, min, max)

But they are such common operations, and have their own mathematical names, I think they warrant inclusion.

Math.normalize = function normalize(value, min, max) {
  return (value - min) / (max - min);
};
Math.lerp = function lerp(norm, min, max) {
  return (max - min) * norm + min;
};

console.assert(Math.normalize(15, 10, 20), 0.5)
console.assert(Math.lerp(0.5, 10, 20), 15)
@Rudxain
Copy link

Rudxain commented Apr 29, 2022

I'll list a summary of what I currently know and think about it:

Pros

  • Shorter, more concise code
  • Possibly a slight performance increase
  • Precision-preserving, because less arithmetic is needed to calculate it, and thus less rounding-errors
  • Increased likelihood of devs recognizing the methods because of their names

Cons

  • Slightly "pollutes" the Math namespace because the methods are easily replaceable
  • More names to remember
  • Less likelihood to be approved by the comitee, because they're too specialized and defined in terms of another method that's currently a proposal

I think I'm wrong about at least 1 of these, please let me know any mistakes.
I'll add more to both lists if I get requests to do so

@Rudxain
Copy link

Rudxain commented Aug 31, 2023

Petition to add variadic relative normalization:

Math.normRelative = (...values) => {
	const min = Math.min(...values)
	const max = Math.max(...values)
	return values.map(
		x => (x - min) * 2 / (max - min) - 1
	)
}

This scales each value to the range [-1,+1], from a range relative to the minimum and maximum values themselves.

I'm aware that a Math.* method returning an Array is controversial, since every method should return a Number

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants