This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Sampling bug in uniform_real (random)


Hello,

There is a bug in the generation code of the class uniform_real
(uniform_real::operator()(somerng) ).  The range of the random number
generator used is not used so generated samples are not in the expected
range at all.  The patch provide a basic fix.

The sample program generate 1000 samples from the uniform distribution
on [0,1], displays them and compute the mean an variance
(approximately 0.5 et 0.83 are expected).

Gabriel

Index: include/tr1_impl/random
===================================================================
--- include/tr1_impl/random	(révision 143495)
+++ include/tr1_impl/random	(copie de travail)
@@ -2096,7 +2096,7 @@
       template<class _UniformRandomNumberGenerator>
         result_type
         operator()(_UniformRandomNumberGenerator& __urng)
-        { return (__urng() * (_M_max - _M_min)) + _M_min; }
+        { return ( (__urng()-__urng.min()) * (_M_max - _M_min)) /(__urng.max()-__urng.min()) ) + _M_min; }
 
       /**
        * Inserts a %uniform_real random number distribution @p __x into the
Index: ChangeLog
===================================================================
--- ChangeLog	(révision 143495)
+++ ChangeLog	(copie de travail)
@@ -1,3 +1,7 @@
+2009-01-19 Gabriel Corona  <gabriel.corona@enst-bretagne>
+
+	* include/tr1_impl/random : Fix sampling of uniform_real.
+
 2009-01-18  Jonathan Wakely  <jwakely.gcc@gmail.com>
 
 	* include/std/thread (__thread_data_base::__run): Make non-const.
#include <cmath>

#include <vector>
#include <algorithm>
#include <numeric>
#include <random>
#include <iostream>

int
main(int argc, char** argv)
{ 
  std::random_device random;
  const int size = 10000;
  std::uniform_real< double > uniform;

  // Generate samples
  std::vector<double> vals( size );  
  for(auto i = vals.begin(); i!=vals.end(); ++i)
    *i = uniform(random);

  // Display samples
  for(auto i = vals.begin(); i!=vals.end(); ++i)
    std::cout << *i << '\n';

  // Mean
  double mean = std::accumulate( vals.begin(), vals.end(), 0.0 ) / size;
  std::cout << "Mean : " << mean << '\n';
  double mean2 = mean*mean;

  // Variance
  double var = 0.0;
  for( auto i =vals.cbegin(); i!=vals.cend(); ++i )
    var += (*i)*(*i) - mean2;
  var /= (size-1);
  std::cout << "Variance : " << var << '\n';
  std::cout << "Deviation : "  << std::sqrt( var ) << '\n';  

  return 0;
};

Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]