Re: Fastest way to normalize doubles and convert to float?
k04jg02@gmail.com wrote:
I have a huge array of doubles. I want to normalize them to the range
-1 to 1 converting them to floats in the process. Is there a 'best' /
fastest way to do this? Does C++ provide a way out of the box?
Some of the previous answers don't normalize to [-1, +1] as specified.
class normalizer
{
double min_, max_;
public:
normalizer(double min, double max) : min_(min), max_(max) { }
double operator()(double x) const {
return (2 * x - max_ - min_) / (max_ - min_);
}
};
// use case: std::transform(begin, end, out, normalizer(min, max))
#include <algorithm>
#include <iterator>
#include <ostream>
#include <iostream>
int main()
{
double array[] = { +0.1139, +1.0668, +0.0593, -0.0956, -0.8323 };
double* array_end = array + sizeof(array) / sizeof(*array);
std::ostream_iterator<double> osi(std::cout, " ");
std::copy(array, array_end, osi);
std::cout << '\n';
double* min = std::min_element(array, array_end);
double* max = std::max_element(array, array_end);
std::transform(array, array_end, array, normalizer(*min, *max));
std::copy(array, array_end, osi);
std::cout << '\n';
}
--
Seungbeom Kim
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]