Random numbers
Random numbers
You are encouraged to solve this task according to the task description, using any language you may know.
You are encouraged to solve this task according to the task description, using any language you may know.
The goal of this task is to generate a 1000-element array (vector, list, whatever it's called in your language) filled with normally distributed random numbers with a mean of 1.0 and a standard deviation of 0.5
C++
#include <cstdlib> // for rand #include <cmath> // for atan, sqrt, log, cos #include <algorithm> // for generate_n double const pi = 4*std::atan(1.0); // simple functor for normal distribution class normal_distribution { public: normal_distribution(double m, double s): mu(m), sigma(s) {} double operator() // returns a single normally distributed number { double r1 = (std::rand() + 1.0)/(RAND_MAX + 1.0); // gives equal distribution in (0, 1] double r2 = (std::rand() + 1.0)/(RAND_MAX + 1.0); return mu + sigma * std::sqrt(-2*std::log(r1))*std::cos(2*pi*r2); } private: double mu, sigma; }; int main() { double array[1000]; std::generate_n(array, 1000, normal_distribution(1.0, 0.5)); }
Java
double[] list = new double[1000]; Random rng = new Random(); for(int i = 0;i<list.length;i++) { list[i] = 1.0 + 0.5 * rng.nextGaussian() }
IDL
result = 1.0 + 0.5*randomn(seed,1000)
Tcl
proc nrand {} {return [expr sqrt(-2*log(rand()))*cos(4*acos(0)*rand())]} for {set i 0} {$i < 1000} {incr i} {lappend result [expr 1+.5*nrand()]}
Python
import random randList = [random.gauss(1, .5) for i in range(1000)]