Did I do the code correctly for my C++ homework for generating floating point random variables?

Generate 2,000,000 normally distributed random numbers using the Box-Muller's method.
I'm pretty new to coding and worked through this with a friend but I'm not sure if I got it right. Thanks

int main()
{
const int nrolls=10; // number of experiments
const int nstars=10; // maximum number of stars to distribute

std::default_random_engine generator;
std::normal_distribution<double> distribution(5.0,2.0);

int p[10]={};

for (int i=0; i<nrolls; ++i) {
double number = distribution(generator);
if ((number>=0.0)&&(number<10.0)) ++p[int(number)];
}

std::cout << "normal_distribution (5.0,2.0):" << std::endl;

for (int i=0; i<10; ++i) {
std::cout << i << "-" << (i+1) << ": ";
std::cout << std::string(p[i]*nstars/nrolls,'*') << std::endl;
}

return 0;
}
To be an acceptable solution for a homework assignment, your code needs to make use of the concepts taught in class. Random programmers on the internet can't tell if it does.

Your code appears to be a basic demo of std::normal_distribution copied from http://www.cplusplus.com/reference/random/normal_distribution and definitely doesn't demonstrate
mjoy wrote:
using the Box-Muller's method
unless the standard library imlementation of std::normal_distribution::operator() does, which is unlikely: both GNU and LLVM seem to be using Marsaglia method internally.
Last edited on
Supposedly c++11 uses the box-muller. The internet said so, so it must be correct :)

The above looks correct. There are several similar implementations on the web and they generally look like what you did. Ill leave it to you to compare what you have against what is out there and determine the correctness.

Topic archived. No new replies allowed.