I need to generate a random number between 0.0 and 1.0. But i'm having problems with it. I've tried a few options but each one gives me the same output which is not between 0.0 and 1.0.
I'm using a seed of 100 as well as the srand() function.
Here is my most recent attempt:
1 2 3 4
double min = 0.0;
double max = 1.0;
random_number = min + rand() / (max + 0.1 - min);
cout << random_number << endl;
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <random>
#include <chrono>
usingnamespace std;
// random_device() doesn't work on many systems
int main()
{
unsignedint seed( chrono::system_clock::now().time_since_epoch().count() );
constint N = 5;
constdouble minimum = 0.0, maximum = 1.0;
// Using rand()
srand( seed );
cout << N << " random numbers in [ " << minimum << ", " << maximum << " ] using rand():\n";
for ( int i = 0; i < N; i++ ) cout << minimum + ( maximum - minimum ) * rand() / RAND_MAX << '\n';
// Using functions in <random>
mt19937 gen( seed );
uniform_real_distribution<double> dist( minimum, maximum );
cout << N << " random numbers in [ " << minimum << ", " << maximum << " ] using <random>:\n";
for ( int i = 0; i < N; i++ ) cout << dist( gen ) << '\n';
}
#include <iostream>
#include <cstdlib>
#include <ctime>
double canonical_random_number()
{
double S = std::rand() ;
constdouble R = RAND_MAX + 1.0 ;
double M = 1.0 ;
for( int i = 1 ; i < 16 ; ++i )
{
S += std::rand() * M ;
M *= R ;
}
return S / M ;
}
int main()
{
std::srand( std::time(0) ) ;
double min = 1.9, max = 0.0 ;
for( int i = 0 ; i < 25 ; ++i )
{
for( int i = 0 ; i < 40 ; ++i )
{
constdouble r = canonical_random_number() ;
if( r > max ) max = r ;
if( r < min ) min = r ;
std::cout << std::fixed << r << ' ' ;
}
std::cout << '\n' ;
}
std::cout << "min: " << min << " max: " << max << '\n' ;
}