Skip to content

Commit

Permalink
normal generator refractored
Browse files Browse the repository at this point in the history
  • Loading branch information
dancixx committed Apr 10, 2022
1 parent 8a0e6e4 commit 8eb928b
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 8 deletions.
35 changes: 30 additions & 5 deletions src/normal.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,32 @@
class normal {
boxMuller = () =>
Math.sqrt(-2 * Math.log(1 - Math.random())) *
Math.cos(2 * Math.PI * Math.random());
}
type NormalMethods = 'BOX_MULLER';

/**
*
* @param {number} m
* @param {number} sigma
* @param {NormalMethods} method
* @returns {number}
*
* @description
* This function returns a sample from normal distribution.
* Default is generated a N(0, 1) sample based on Box-Müller tranformation.
*/

const normal = (
m: number = 0,
sigma: number = 1,
method: NormalMethods = 'BOX_MULLER',
): number => {
let sample: number = 0;

if (method === 'BOX_MULLER') {
const u = Math.random();
const v = Math.random();

sample = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
}

return sample * sigma + m;
};

export default normal;
4 changes: 1 addition & 3 deletions src/wiener.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import normal from './normal';
import ou from './ou';

const norm = new normal();

/**
*
* @param {number} n
Expand All @@ -18,7 +16,7 @@ const wiener = (
let W: number[] = new Array(n).fill(0);

for (let index = 0; index < n - 1; index++) {
dW[index] = Math.sqrt(dt) * norm.boxMuller();
dW[index] = Math.sqrt(dt) * normal();
W[index + 1] = W[index] + dW[index];
}

Expand Down

0 comments on commit 8eb928b

Please sign in to comment.