/* Sum to one in Picat. https://brainstellar.com/puzzles/probability/213 """ On pressing a button, a random number is generated uniformly between 0 & 1. You keep on generating these numbers until their sum exceeds 1. What is the probability that you need to press the button more than n times? What is the expected number of times you need to press the button? Answer: Probability: 1/n! ; Expected times: e """ Cf https://math.stackexchange.com/questions/111314/choose-a-random-number-between-0-and-1-and-record-its-value-keep-doing-it-u/111343#111343 Cf my Gamble model gamble_sum_to_one.rkt This program was created by Hakan Kjellerstrand, hakank@gmail.com See also my Picat page: http://www.hakank.org/picat/ */ import ppl_distributions, ppl_utils. import util. main => go. /* [expected_theoretical = 2.71828,p_more_than_3_times = 0.166667] var : len Probabilities: 2: 0.4972000000000000 3: 0.3351500000000000 4: 0.1243000000000000 5: 0.0346500000000000 6: 0.0071500000000000 7: 0.0013000000000000 8: 0.0002500000000000 mean = 2.7243 var : more than 2 times Probabilities: 1: 0.5028000000000000 0: 0.4972000000000000 mean = 0.5028 var : more than 3 times Probabilities: 0: 0.8323500000000000 1: 0.1676500000000000 mean = 0.16765 var : more than 4 times Probabilities: 0: 0.9566500000000000 1: 0.0433500000000000 mean = 0.04335 var : more than 5 times Probabilities: 0: 0.9913000000000000 1: 0.0087000000000000 mean = 0.0087 */ go ?=> println([expected_theoretical=exp(1),p_more_than_3_times=(1/factorial(3))]), reset_store, run_model(20_000,$model,[show_probs_trunc,mean]), nl, % show_store_lengths,nl, % fail, nl. go => true. model() => A = [], OK = false, while (OK == false) if A.sum > 1 then OK := A else A := A ++ [beta_dist(1,1)] end end, Len = A.len, add("len",Len), foreach(I in 2..5) add("more than " ++ I.to_string ++ " times",check1(Len > I)) end.