0

I have an unordered array of numbers, and I want to find where a variable sits within that range of numbers, and express it as a number between 0 and 1.

  • If the variable is the highest number in the array output 1.
  • If the variable is the lowest number in the array output 0.
  • If the variable is midway between the highest and lowest numbers in the array output 0.5.

I was going to use min() and max() to find the highest and lowest points of the array, and then run a calculation based on that... but I'm stumped for finding where the variable sits within the array and expressing it as a number between 0 and 1.

For example:

$my_array = array( 2.51, 3.63, 10.98, 6.39, 1.54, 6.02 );

$find_this = 3.63;

function compare_to_range {
  $highest = max($my_array);
  $lowest = min($my_array);

  Something to show where $find_this sits within those two points.
}
1
  • What do you mean Something to show where $find_this sits within those two points.? Based on your above explanation, if 3.63 is not the highest or lowest value, you said you wanted to return 0.5? Commented May 8, 2018 at 6:08

1 Answer 1

2

If you want to just find how big is the number compared to the others (not find its position in the array), computing ($find_this - $lowest) / ($highest - $lowest) should work.

It returns 0 for minimum, 1 for maximum and the ratio for all other values (of the value is exactly the average of minimum and maximum, you get 0.5).

Sign up to request clarification or add additional context in comments.

2 Comments

I feel a stupid asking this, but I can't figure it out. On my scale I always need 1 to be "good" and 0 to be "bad". Your calculation works perfect when a higher number is desirable (e.g. comparing speeds) because the highest number in the array will always score 1. But now I need a calculation on that same scale (1=good, 0=bad) where the lowest number in a range is desirable (e.g. comparing prices, the lower the better), so this time the lowest number in the array should always score 1 and the highest number should score 0.
I think that ($find_this - $highest) / ($lowest - $highest) should work. You can imagine the first answer as moving the range towards zero (lowest value will get to 0) and then normalizing it (so that maximum values is 1). This is similar - we move the range towards zero, but as we want to inverse it, we move it pass zero (highest value gets moved to 0). And then we also normalize it, but as we don't want the answer to be negative, we are dividing by a negative number (lowest - highest)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.