Last active
December 3, 2016 08:51
-
-
Save voltrevo/278645696e1c0a4934749ab08471bb21 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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]); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: