How to pick an item by its probability?

Generate a uniformly distributed random number. Iterate through your list until the cumulative probability of the visited elements is greater than the random number Sample code: double p = Math.random(); double cumulativeProbability = 0.0; for (Item item : items) { cumulativeProbability += item.probability(); if (p <= cumulativeProbability) { return item; } }

Select k random elements from a list whose elements have weights

If the sampling is with replacement, you can use this algorithm (implemented here in Python): import random items = [(10, “low”), (100, “mid”), (890, “large”)] def weighted_sample(items, n): total = float(sum(w for w, v in items)) i = 0 w, v = items[0] while n: x = total * (1 – random.random() ** (1.0 / … Read more

How to calculate probability in a normal distribution given mean & standard deviation?

There’s one in scipy.stats: >>> import scipy.stats >>> scipy.stats.norm(0, 1) <scipy.stats.distributions.rv_frozen object at 0x928352c> >>> scipy.stats.norm(0, 1).pdf(0) 0.3989422804014327 >>> scipy.stats.norm(0, 1).cdf(0) 0.5 >>> scipy.stats.norm(100, 12) <scipy.stats.distributions.rv_frozen object at 0x928352c> >>> scipy.stats.norm(100, 12).pdf(98) 0.032786643008494994 >>> scipy.stats.norm(100, 12).cdf(98) 0.43381616738909634 >>> scipy.stats.norm(100, 12).cdf(100) 0.5 [One thing to beware of — just a tip — is that the parameter … Read more

Why does this random value have a 25/75 distribution instead of 50/50?

Because nextDouble works like this: (source) public double nextDouble() { return (((long) next(26) << 27) + next(27)) / (double) (1L << 53); } next(x) makes x random bits. Now why does this matter? Because about half the numbers generated by the first part (before the division) are less than 1L << 52, and therefore their … Read more

Data structures for loaded dice?

You are looking for the alias method which provides a O(1) method for generating a fixed discrete probability distribution (assuming you can access entries in an array of length n in constant time) with a one-time O(n) set-up. You can find it documented in chapter 3 (PDF) of “Non-Uniform Random Variate Generation” by Luc Devroye. … Read more

Minimizing NExpectation for a custom distribution in Mathematica

As far as I see, the problem is (as you already wrote), that MeanResidualLife takes a long time to compute, even for a single evaluation. Now, the FindMinimum or similar functions try to find a minimum to the function. Finding a minimum requires either to set the first derivative of the function zero and solve … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)