5 ms·
Messed around with numbers until they made sense. Your suggestion is a very smart one for a very dumb thing. Let me see what I can do.
by lanewinfield 5y ago
Messed around with numbers until they made sense. Your suggestion is a very smart one for a very dumb thing. Let me see what I can do.
- pkulak 5y ago> Your suggestion is a very smart one for a very dumb thing. lol, I love HN so much.
- crdrost 5y agoHeh. I can quote the answer as the answer is easy. If you want the time between the last sound and the next sound to average T, schedule the next sound to begin at next = last - T*Math.ln(Math.random()) Explaining why this is correct requires a bit of calculus and a couple perspectives from probability theory... To give a quick outline, if this were discrete timesteps then the answer would look like this: given that one event has a probability p of happening, then the probability it happens after exactly n tries is (1–p)^{n–1} * p Since it has to not happen independently n–1 times. Then we want to scale this to N tries per unit time so the timestep dt = 1/N... Evidently p needs to also decrease and we assume it just scales down with the timestep, p=k dt, t = n dt, so n = N t. Making those substitutions one gets the defining expression for e^x and so the probability that the event happens between time t and t+dt is, in the limit, k dt e^{-kt}. We can then integrate this to confirm that it is normalized and to discover that its mean is 1/k. Then coming from the other side, the probability of the given expression being between t and t+dt is the probability that Math.random() falls between A and B, which is just B–A. Some more calculus gives the exact same expression with k=1/T, bada bing bada boom.
- CraigJPerry 5y agoThat’s a neat solution, my instinct would have been futzing with the universal distribution of Math.random() into a normal distribution (incurring even more cost than the Math.log() call in the process).
- jtolmar 5y agoIf I recall correctly, this will get you a standard deviation of 1. let result = 0; for (let i = 0; i < 6; i++) { result += Math.random() - Math.random(); } return result; Obviously this costs 12x as much as Math.random() itself, but it sure is simple. (It'll also never return anything more than 6 standard deviations away from the mean, but it's not like you actually want that in most applications.)