Skip to content

Instantly share code, notes, and snippets.

@voltrevo
Last active December 3, 2016 08:51
Show Gist options
  • Save voltrevo/278645696e1c0a4934749ab08471bb21 to your computer and use it in GitHub Desktop.
Save voltrevo/278645696e1c0a4934749ab08471bb21 to your computer and use it in GitHub Desktop.
'use strict';
const range = (n) => (new Array(n)).fill(0).map((x, i) => i);
const stdNormalRand = () => {
const u = 1 - Math.random(); // Subtraction to flip [0, 1) to (0, 1].
const v = 1 - Math.random();
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
};
const roundSigFigs = (x, figs) => {
const shift = Math.ceil(Math.log(x) / Math.log(10));
const powShift = Math.pow(10, shift);
const xSmall = x / powShift;
const powFigs = Math.pow(10, figs);
const xSmallRound = Math.round(xSmall * powFigs) / powFigs;
return xSmallRound * powShift;
};
const formatMoney = (n, len) => {
n = Math.round(roundSigFigs(n, 3));
const nStr = n.toString();
const chars = range(len).fill(' ');
let pos = 0;
for (let i = 0; i < len && i < nStr.length; i++) {
chars[len - 1 - pos] = nStr[nStr.length - 1 - i];
pos++;
if (i % 3 === 2) {
chars[len - 1 - pos] = ',';
pos++;
}
}
if (chars[len - pos] === ',') {
chars[len - pos] = ' ';
}
return '$' + chars.join('');
};
const createGiftSequence = (M, CP0, r, N, U) => {
const L = range(N).map(() => Math.pow(U, stdNormalRand()));
const CP = range(N).map(i => CP0 * Math.pow(r, i));
const LCPSum = range(N).map(i => L[i] * CP[i]).reduce((a, b) => a + b);
const k = M / LCPSum;
return range(N).map(i => k * L[i] * CP[i]);
};
@voltrevo
Copy link
Author

voltrevo commented Dec 3, 2016

Example:

> console.log('\n' + createGiftSequence(10 * 1e6, 1, 0.9, 50, 2).map(g => formatMoney(g, 10)).join('\n'));
$   835,000
$   512,000
$   681,000
$   847,000
$   518,000
$ 1,580,000
$   320,000
$   467,000
$   464,000
$   352,000
$   339,000
$   512,000
$    91,100
$   190,000
$   259,000
$   402,000
$   163,000
$   165,000
$   293,000
$    58,900
$    75,000
$    58,300
$   118,000
$    75,000
$    69,200
$    44,300
$    71,400
$     7,730
$    20,400
$    52,300
$    57,800
$    32,600
$    10,800
$    40,300
$    14,100
$    14,400
$     8,600
$     7,550
$    37,600
$    18,600
$    16,200
$    13,900
$     9,240
$    14,700
$     8,330
$     5,880
$    11,000
$    12,400
$     7,250
$    20,300

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment