# (C++) Rescale

Rescale is a math code snippet to rescale a double, 1D std::vector or 2D std::vector from a certain range to a new range.

## Rescale on a double

 ``` #include #include //From http://www.richelbilderbeek.nl/CppRescale.htm const double Rescale(   const double value,   const double oldMin,   const double oldMax,   const double newMin,   const double newMax) {   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; } ```

## Rescale on a 1D std::vector

 ``` #include #include #include //From http://www.richelbilderbeek.nl/CppRescale.htm const std::vector Rescale(   std::vector v,   const double newMin,   const double newMax) {   const double oldMin = *std::min_element(v.begin(),v.end());   const double oldMax = *std::max_element(v.begin(),v.end());   typedef std::vector::iterator Iter;   Iter i = v.begin();   const Iter j = v.end();   for ( ; i!=j; ++i)   {     *i = Rescale(*i,oldMin,oldMax,newMin,newMax);   }   return v; } ```

## Rescale on a 2D std::vector

 ``` #include #include #include //From http://www.richelbilderbeek.nl/CppRescale.htm const std::vector > Rescale(   std::vector > v,   const double newMin,   const double newMax) {   const double oldMin = MinElement(v);   const double oldMax = MaxElement(v);   typedef std::vector >::iterator RowIter;   RowIter y = v.begin();   const RowIter maxy = v.end();   for ( ; y!=maxy; ++y)   {     typedef std::vector::iterator ColIter;     ColIter x = y->begin();     const ColIter maxx = y->end();     for ( ; x!=maxx; ++x)     {       *x = Rescale(*x,oldMin,oldMax,newMin,newMax);     }   }   return v; } ``` This page has been created by the tool CodeToHtml