How to resolve the algorithm Probabilistic choice step by step in the FutureBasic programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Probabilistic choice step by step in the FutureBasic programming language
Table of Contents
Problem Statement
Given a mapping between items and their required probability of occurrence, generate a million items randomly subject to the given probabilities and compare the target probability of occurrence versus the generated values. The total of all the probabilities should equal one. (Because floating point arithmetic is involved, this is subject to rounding errors).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Probabilistic choice step by step in the FutureBasic programming language
Source code in the futurebasic programming language
_elements = 8
local fn ProbabilisticChoice
double prob(_elements), cumulative(_elements)
Str15 item(_elements)
double r, p, sum = 0, checksum = 0
long i, j, samples = 1000000
item(1) = "aleph" : item(2) = "beth" : item(3) = "gimel" : item(4) = "daleth"
item(5) = "he" : item(6) = "waw" : item(7) = "zayin" : item(8) = "heth"
prob(1) = 1/5.0 : prob(2) = 1/6.0 : prob(3) = 1/7.0 : prob(4) = 1/8.0
prob(5) = 1/9.0 : prob(6) = 1/10.0 : prob(7) = 1/11.0 : prob(8) = 1759/27720
for i = 1 to _elements
sum += prob(i)
next
if abs(sum-1) > samples then print "Probabilities don't sum to 1." : exit fn
for i = 1 to samples
cln r = (((double)arc4random()/0x100000000));
p = 0
for j = 1 to _elements
p += prob(j)
if (r < p) then cumulative(j) += 1 : exit for
next
next
print
printf @"Item Actual Theoretical"
printf @"---- ------ -----------"
for i = 1 to _elements
printf @"%-7s %10.6f %12.6f", item(i), cumulative(i)/samples, prob(i)
checksum += cumulative(i)/samples
next
printf @" -------- -----------"
printf @"%17.6f %12.6f", checksum, 1.000000
end fn
fn ProbabilisticChoice
HandleEvents
You may also check:How to resolve the algorithm Associative array/Iteration step by step in the Groovy programming language
You may also check:How to resolve the algorithm Knapsack problem/0-1 step by step in the 11l programming language
You may also check:How to resolve the algorithm String case step by step in the Octave programming language
You may also check:How to resolve the algorithm SHA-256 step by step in the Python programming language
You may also check:How to resolve the algorithm Random Latin squares step by step in the Arturo programming language