How to calculate a value in a given range?

Asked

Viewed 273 times

-1

I have to make the following calculation:
I have an input number (say 1.3), which is in my range A, which goes from 0 to 3, and I need a corresponding value in range b (which is inversely proportional), which goes from 3 to 1.
How can I calculate, starting from two ranges, a range B value that correlates to the input value that is in range A?
Example:
Range A: (0 - 3)
Range B: (3 - 1)
Range A past value: 1.5
Expected return value: 2

1 answer

3


You’re looking for something inversely proportional. It’s more math than programming, but putting it into code:

Considering:

  • A_max the maximum value of range A (3)
  • A_min the minimum value of range A (0)
  • B_max the maximum value of range B (3)
  • B_min the minimum value of range B (1)

We have:

output = ((input - A_min)*(B_max - B_min)) / (A_max - A_min) + B_min;

  • Thanks, buddy, you solved the problem. (I only have to remember to invert the maximum and minimum values of B to get the right result, but it has helped too much)

  • I didn’t understand how the ranges were arranged (whether it was an ordered array or not), so I decided not to complicate the code and leave it more open for its implementation. But I’m glad I could help you =)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.