# ConvertRange function, need some help with it.

• 06-18-2004
Eber Kain
ConvertRange function, need some help with it.
I cant figure out a good way of doing this one.

Code:

```int ConvertRange(float fmin, float fmax, float cur, int imin, int imax) {         int i;                 return i; }```
It should take the range of fmin to fmax and the relitave position cur, and return a relitave position that is from imin to imax.

EXAMPLE
fmin = 0.0f
fmax = 1.0f
cur = 0.1
imin = 0
imax = 10
return = 1
• 06-18-2004
The first step would seem to be a better definition of the problem. For example, is the range fmin to fmax the same as imin to imax, or is imim to imax inclusive but not necessarily the same as the range from fmin to fmax, or can fmin be less than imin or fmax larger than imax? Is the return value supposed to be the next biggest integer above cur but less than or the same as imax or is the return value determined by some other protocol?
• 06-18-2004
Codeplug
Use percentages...
Code:

```Range A [1 - 10] Range B [50 - 100] If a value in range A is 4, what is the relative value in range B? Determine the length of A 10 - 1 + 1 = 10 Normalize the A range value to 0 by subtracting the range start 4 - 1 = 3 Determine the percentage of 3 out of 10 (length of A) (3 * 100) / 10 = 30% What value is "30% into" range B? Determine the length of B 100 - 50 + 1 = 51 Determine 30% of 51 (30 * 51) / 100 = 15.3 Add that value to the range start of B 50 + 15.3 = 65.3```
For the least amount of %error, use doubles for your calculations. Round your final awnser and truncate it to an integer.

gg
• 06-18-2004
Eber Kain
No, the ranges are necessarly the same. fmin will allways be smaller than fmax, and imin will allways be smaller than imax.

Here is what I came up with... It works, but only for positive values, which is sufficient for now.
Code:

```int ConvertRange(float fmin, float fmax, float cur, int imin, int imax) {         fmax -= fmin;                                //makes the range from 0 to fmax         cur -= fmin;         float foff = 1.0f - fmax;        //the ammount to change fmax to make it from 0 to 1, make it % based         cur += cur*foff;                        //fix cur so it stays in the right position in the relitave range         fmax += foff;                                //fmax should be 1.0f / 100%         float ir = imax-imin;                //integer range         int i = imin + (int)(ir*cur+0.5);         return i; }```
• 06-18-2004
Eber Kain
Revised after reading codeplugs post again :)

Code:

```int ConvertRange(float fmin, float fmax, float cur, int imin, int imax) {         float per = (cur - fmin) / (fmax - fmin);         int i = per * (float)(imax - imin);         return i + imin; }```
• 06-18-2004
swoopy
Yeah, that looks good, and it's actually readable. I came up with this:
return imin + static_cast<int> ((imax-imin) / (fmax-fmin) * (cur-fmin));

but I think yours is more readable.