normal distribution

I wrote the following program shown below that produces a normally distributed random number several times, and then takes the average of them. The problem that I have been having though is that the output it has been producing is 0.0288385 despite the fact that I set the mean of the normal distribution to be 0.1. Does anybody know why this output value would be so far off from 0.1 despite having averaged over such a large number of random numbers namely 10,000 of them? Also does anyone know how to randomly seed this random number generator such that it gives a different value each time its run perhaps by seeding it with the windows timer? Below is the program.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <random>


using namespace std;

int main()
{
    default_random_engine generator;
    normal_distribution<double> distribution1(0.1,3.0);
    double number1,sum,n;
    n=10000;
    sum=0;
    double i;

    for(i=0;i<n;i++)
    {
    number1= distribution1(generator);
    sum=sum+number1;
    }
    cout <<sum/n<< endl;
    return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <chrono>
#include <random>

int main()
{
    std::default_random_engine generator( std::random_device{}() ) ;
    // or, if we do not have a true std::random_device: 
    // const auto seed = std::chrono::high_resolution_clock::now().time_since_epoch().count() ;
    // std::default_random_engine generator(seed) ;
    
    std::normal_distribution<double> distribution1(0.1,3.0);

    const int n = 1000000 ;
    double sum = 0 ;
    for( int i = 0 ; i < n ; ++i ) sum += distribution1(generator) ;
    std::cout << sum / n << '\n' ;
}

http://coliru.stacked-crooked.com/a/b7a7028f4d62d883
The default seed is usually no good. You can use std::time to seed the engine.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <random>
#include <ctime>

using namespace std;

int main()
{
    default_random_engine generator(time(0));
    normal_distribution<double> distribution1(0.1,3.0);
    double number1,sum,n;
    n=10000;
    sum=0;
    double i;

    for(i=0;i<n;i++)
    {
    number1= distribution1(generator);
    sum=sum+number1;
    }
    cout <<sum/n<< endl;
    return 0;
}
Topic archived. No new replies allowed.