Sadiksha Gautam
Sadiksha Gautam

Reputation: 5152

normal() is always giving negative value

I am using normal(mean, sigma) to generate random number for normal distribution with mean and sigma. My sigma is 8db and mean is 0. But I always get negative value when I do normal(mean, sigma). Is there any way I can get positive number for this?

Upvotes: 1

Views: 373

Answers (2)

Prashant Kumar
Prashant Kumar

Reputation: 22549

You do not simply call normal(double mean, double sigma).
Instead, call double r8_normal ( double a, double b, int &seed ), where a is the mean, b is the sigma, and seed initializes the random number generator.

I was able to compile and use the Normal library in the link you provided.
I downloaded normal.cpp and normal.hpp. These are old files, mostly translations from Fortran.
I had to modify normal.hpp by adding #include <complex> and changing complex to std::complex in the first two declarations to get it to compile for me at low warning levels.

Then I created a test driver:

#include "normal.hpp"
#include <iostream>

int main() {
    int seed = 123;
    std::cout << r8_normal (0.0, 8.0, seed) << '\n'
              << r8_normal (0.0, 8.0, seed) << '\n'
              << r8_normal (0.0, 8.0, seed) << '\n'
              << r8_normal (0.0, 8.0, seed) << '\n'
              << r8_normal (0.0, 8.0, seed) << '\n';
}

which gives this output

8.19933
1.45505
-2.42428
26.9111
12.8398

And everything looks like it's working for me for mean = 0.0, sigma = 8.0.

Upvotes: 2

MoRe
MoRe

Reputation: 1538

I only now read that you set mean to 0 and sigma to 8. I thought it was the other way round. So negative values are expected, not all the time though.

The random number generation is only pseudo random so if you only generate a few values and seed the generator with the same constant every time you might only experience negative values.

Try setting your seed using the current system time or generate a large number of random numbers to see if you really ONLY get negative values.

Upvotes: 2

Related Questions