Skip to content

Random Normal Number

Query Source: adopted from here

Introduction

Normal distribution is one of the most common distributions in statistics. Drawing one or multiple random numbers from a normal distribution is an often used technique in Monte Carlo simulation. Generating a random normal number is implemented in most programming languages. One algorithm used to generate a standard normal random number is Box-Muller transformation, which generates a pair of random numbers from a standard normal distribution.

Box-Muller Algorithm

Algorithm

  1. a:=\sqrt{-2 \cdot ln(U_1)}
  2. b:=2 \pi \cdot U_2
  3. return [a \cdot sin(b), a \cdot cos(b)]

where U_1 and U_2 are two independent uniform random variables.

Question

Write a q function to generate a list of random numbers from a standard normal distribution.

genNormalNumber[5] / Returns a list of 5 normal random numbers

Answer

Below is the suggested answer:

genNormalNumber:{
    pi:acos -1;
    $[x=2*n:x div 2;
      raze sqrt[-2*log n?1f]*/:(sin;cos)@\:(2*pi)*n?1f;
      -1_.z.s 1+x
    ]
  };

Explanations:

  • Line 1 uses the inverse trigonometric functions to find \pi.
  • Line 2 use an if-else ($) to check whether the request number of random numbers is odd or even. Since the Box-Muller transformation always returns two random normal numbers, so a number has to be dropped if the input argument is an odd number. This is achieved by line 4. Note that .z.s is the function itself.
  • Line 3 handles the case when input argument is an event number.