Map range: Difference between revisions
(C++ example.) |
(Added to the task description.) |
||
Line 1: | Line 1: | ||
{{draft task}}Given two [[wp:Interval (mathematics)|ranges]]: |
|||
{{draft task}}Given two ranges [A1,A2], [B1,B2], and a value within range [A1,A2], map that value to its corresponding position within [B1,B2]. |
|||
* Range <math>a</math> of all real numbers <math>x</math> satisfying <math>a1 \le x \le a2</math>. |
|||
⚫ | |||
* And range <math>b</math> of all real numbers <math>y</math> satisfying <math>b1 \le y \le b2</math>. |
|||
Then a value s in range a is linearly mapped to a value t in range b where: |
|||
:<math>t = b1 + {(s - a1)(b2 - b1) \over (a2 - a1)}</math> |
|||
The task is to write a function/subroutine/... that takes two ranges and a real number and returns the mapping of the real number from the first to the second range. Use this function to map the values of the integers 0 to 10 from the range [0, 10] to the range [-1, 0] in succession. |
|||
⚫ | |||
=={{header|C++}}== |
=={{header|C++}}== |
Revision as of 18:14, 25 November 2010
Given two ranges:
- Range of all real numbers satisfying .
- And range of all real numbers satisfying .
Then a value s in range a is linearly mapped to a value t in range b where:
The task is to write a function/subroutine/... that takes two ranges and a real number and returns the mapping of the real number from the first to the second range. Use this function to map the values of the integers 0 to 10 from the range [0, 10] to the range [-1, 0] in succession.
C++
This example defines a template function to handle the mapping, using two std::pair objects to define the source and destination ranges. It returns the provided value mapped into the target range.
It's not written efficiently; certainly, there can be fewer explicit temporary variables. The use of the template offers a choice in types for precision and accuracy considerations, though one area for improvement might be to allow a different type for intermediate calculations.
<lang cpp>#include <iostream>
- include <utility>
template<typename tVal> tVal map_value(std::pair<tVal,tVal> a, std::pair<tVal, tVal> b, tVal inVal) {
tVal inValNorm = inVal - a.first; tVal aUpperNorm = a.second - a.first; tVal normPosition = inValNorm / aUpperNorm;
tVal bUpperNorm = b.second - b.first; tVal bValNorm = normPosition * bUpperNorm; tVal outVal = b.first + bValNorm;
return outVal;
}
int main()
{
std::pair<float,float> a(0,10), b(-1,0);
for(float value = 0.0; 10.0 >= value; ++value) std::cout << "map_value(" << value << ") = " << map_value(a, b, value) << std::endl;
return 0;
}</lang>
Output:
map_value(0) = -1 map_value(1) = -0.9 map_value(2) = -0.8 map_value(3) = -0.7 map_value(4) = -0.6 map_value(5) = -0.5 map_value(6) = -0.4 map_value(7) = -0.3 map_value(8) = -0.2 map_value(9) = -0.1 map_value(10) = 0