remap-functions

I'm not quite sure where to post this, but here it is. I used to play a little with Processing, and for those of you who know it there is a function called map, which remaps a value from one range to another. I wanted to make my own, and I ended up with:

1
2
3
float remap(float v, float a, float b, float c, float d) {
	return v-(abs(b-a)-abs(d-c))/2.0;
}


But then I took a look at the source for Processing's map-function, and it is quite different:
1
2
3
float map(float value, float istart, float istop, float ostart, float ostop) {
	return ostart + (ostop - ostart) * ((value - istart) / (istop - istart));
}


So I'm wondering; does any of you see anything wrong with my function that I haven't come across yet? And could either of them be considered more efficient?


Fafner
Last edited on
Yes, your implementation doesn't generate the same result in certain cases:
http://ideone.com/poljcA
15
16
std::cout <<   map(5.0, 0.0,10.0, 20.0,40.0) << std::endl; //30.0
std::cout << remap(5.0, 0.0,10.0, 20.0,40.0) << std::endl; //10.0 
The correct value is 30.0
Last edited on
You're right, it doesn't take into account the fact the the new range could be shifted, but if I change it to

1
2
3
float remap(float v, float a, float b, float c, float d) {
	return v-(abs(b-a)-abs(d-c))/2.0+c;
}


it seems to work? :)

EDIT: It doesn't seem to work with negative ranges tho... But thanks anyway :)
Last edited on
The two functions are not equivalent, because your math is wrong.

Yours just subtracts half the difference between the two ranges from the value (and adds the beginning of the new range).

This is surely not giving you the result you want.

The correct map function properly scales the value.

(1) get the offset into the source range of the value
    (value - istart)

(2) convert that to a percentage into the input range
    (value - istart) / (istop - istart)

(3) convert that to an offset into the output range
    (value - istart) / (istop - istart) * (ostop - ostart)

(4) add the offset to the start of the output range
    (value - istart) / (istop - istart) * (ostop - ostart) + ostart

Rearranging the terms to match the map function is trivial.

Hope this helps.
Topic archived. No new replies allowed.