Go back to Richel Bilderbeek's homepage.
Go back to Richel Bilderbeek's C++ page.
Math code snippet to rescale a double, 1D std::vector or 2D std::vector from a certain range to a new range.
* View the code of 'Rescale' on a double in plain text
//From http://www.richelbilderbeek.nl/CppRescale.htm
{
assert(value >= oldMin);
assert(value <= oldMax);
const double oldDistance = oldMax - oldMin;
//At which relative distance is value on oldMin to oldMax ?
const double distance = (value - oldMin) / oldDistance;
assert(distance >= 0.0);
assert(distance <= 1.0);
const double newDistance = newMax - newMin;
const double newValue = newMin + (distance * newDistance);
assert(newValue >= newMin);
assert(newValue <= newMax);
return newValue;
}
* View the code of 'Rescale' on a 1D std::vector in plain text
//From http://www.richelbilderbeek.nl/CppRescale.htm
const std::vector<double> Rescale(
std::vector<double> v,
{
const double oldMin = *std::min_element(v.begin(),v.end());
const double oldMax = *std::max_element(v.begin(),v.end());
typedef std::vector<double>::iterator Iter;
Iter i = v.begin();
const Iter j = v.end();
for ( ; i!=j; ++i)
{
*i = Rescale(*i,oldMin,oldMax,newMin,newMax);
}
return v;
}
* View the code of 'Rescale' on a 2D std::vector in plain text
//From http://www.richelbilderbeek.nl/CppRescale.htm
const std::vector<std::vector<double> > Rescale(
std::vector<std::vector<double> > v,
{
const double oldMin = MinElement(v);
const double oldMax = MaxElement(v);
typedef std::vector<std::vector<double> >::iterator RowIter;
RowIter y = v.begin();
const RowIter maxy = v.end();
for ( ; y!=maxy; ++y)
{
typedef std::vector<double>::iterator ColIter;
ColIter x = y->begin();
const ColIter maxx = y->end();
for ( ; x!=maxx; ++x)
{
*x = Rescale(*x,oldMin,oldMax,newMin,newMax);
}
}
return v;
}
Go back to Richel Bilderbeek's C++ page.
Go back to Richel Bilderbeek's homepage.