Go back to Richel Bilderbeek's homepage.

Go back to Richel Bilderbeek's C++ page.

 

 

 

 

 

(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 <algorithm>
#include <cassert>

//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 <algorithm>
#include <cassert>
#include <vector>

//From http://www.richelbilderbeek.nl/CppRescale.htm
const std::vector<double> Rescale(
  std::vector<double> 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<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;
}

 

 

 

 

 

Rescale on a 2D std::vector

 

#include <algorithm>
#include <cassert>
#include <vector>

//From http://www.richelbilderbeek.nl/CppRescale.htm
const std::vector<std::vector<double> > Rescale(
  std::vector<std::vector<double> > v,
  const double newMin,
  const double newMax)
{
  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.

 

Valid XHTML 1.0 Strict

This page has been created by the tool CodeToHtml