1.0.0 • Published 7 years ago

ndrand v1.0.0

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

ndrand

A class used to generate a nonuniform distribution of random numbers.

Usage

var ndr = require('ndrand');

ndr.initialize([
  {x:0,y:0},
  {x:5,y:5},
  {x:10,y:0},
]);

console.log(ndr.random());

Algorithm Initialization

The user initializes the class with an array of x,y pairs describing the desired distribution. Two consecutive pairs math and math form a trapezoid like so.

trapezoid

Where the height of two sides are math and math respectively and the width is math

The area of the trapeziod is the average of the two heights multiplied by the width and can be written like so.

math

During initialization, we calculate the area of each trapezoid to obtain the total area of the distribution. Along the way we record the cumulative area (cumArea) at each pair. This represents the area of all trapezoids to the left of the current pair. As such, the cumulative area of the first pair is 0 and the cumulative area of the last pair is the total area of the distribution.

We then go back and using the cumulative area of each pair and total area previously computed, calculate the cumulative distribution (cumDist) of each pair. The distribution represents the percentage of numbers in the distribution to the left of the current pair. Consequently, the cumulative distribution of the first pair is 0 and the cumulative distribution of the last pair is 1.0

Generation Algorithm

Given a uniform distributed random (udr) number from 0-1 we treat this as a percentage of the overall area of the nonuniform distribution curve (ndc) and try to find the value math where the ratio of the area of the ndc to left to the total area exactly matches the udr.

We do this by first determining which trapezoid that contains the area we are looking for. This will be the trapezoid formed by the consecutive pairs math and math where the cumDist of math is less than udr and the cumDist of math is greater than udr. From there we calculate the target volume by multiplying the udr by the cumArea of the last pair in the ndc and then subtract the cumArea of the math pair to obtain the math. This is the area of the trapezoid formed by the pairs math and math in the figure below.

partial trapezoid

Given math we can calculate math using the the previous equation for the area of a trapezoid like so.

math where math

substituting math we can simplify this as

math

math

math

math

which is a quadratic equation of the form

math

where

math

math

math

thus we can solve for math using the quadratic equation

math

The term math is called the axis of symetry (aos) whereas math represents the distance (distance) from the aos

The algorithm will add or subtract the distance form the aos to find the value that falls between math and math