Asperger
Asperger

Reputation: 3222

Confusion with combining Math.max and Math.min

There is a formula I have read on stackoverflow and one thing is not clear to me, more on that below. maxMax returns the second value within the brackets and the mathMin the first one.

So let us assume I am making a calculation where let us say:

max = 2 * 10 min = 2 * 5

In order to calculate the max and min in one line I would have to use this formula:

Math.max(a, Math.min(x, b))

The issue I am having is that math.max looks as if it returns math.min in this formula. Does that not destroy the cause of max or am I missunderstanding something?

For example in an application that strictly needs to define a min and max value for something the above formula is correct or not? .

Upvotes: 0

Views: 5067

Answers (2)

Robert
Robert

Reputation: 2669

The naming of the functions Math.min and Math.max is a bit ambiguous.

In order to clip a value to a given range you can use them like this:

clippedValue = Math.max(lowerBound, Math.min(value, upperBound))

Math.max takes an arbitrary amount of numbers and returns the biggest one while Math.min also takes an arbitrary amount of numbers and returns the smallest.

This behavior might be in contradiction to your expectations when you're looking for a way to clip values. Math.min doesn't clip a value to a minimum bound, just as Math.max doesn't clip a value to a maximum bound.

But (accidentally?) they work as desired if you change their names. So Math.max with two arguments works like a hypothetical Math.clipMin, just as Math.min with two argments works like a hypothetical Math.clipMax.

Upvotes: 1

once
once

Reputation: 131

Math.max(a, Math.min(x, b));

Assuming a, b, and x are numbers, Math.min(x,b) is always resolved and number is returned.

Taking the result to Math.max method, action is performed and larger number is returned.

It could also be defined in 2 steps as

var min = Math.min(x, b);
Math.max(a, min);

Reading the above example should be more clear and easier to understand.

See more examples at Math.max() and Math.min()

Upvotes: 2

Related Questions