How to resolve the algorithm Probabilistic choice step by step in the Fortran programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Probabilistic choice step by step in the Fortran 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 Fortran programming language
Source code in the fortran programming language
PROGRAM PROBS
IMPLICIT NONE
INTEGER, PARAMETER :: trials = 1000000
INTEGER :: i, j, probcount(8) = 0
REAL :: expected(8), mapping(8), rnum
CHARACTER(6) :: items(8) = (/ "aleph ", "beth ", "gimel ", "daleth", "he ", "waw ", "zayin ", "heth " /)
expected(1:7) = (/ (1.0/i, i=5,11) /)
expected(8) = 1.0 - SUM(expected(1:7))
mapping(1) = 1.0 / 5.0
DO i = 2, 7
mapping(i) = mapping(i-1) + 1.0/(i+4.0)
END DO
mapping(8) = 1.0
DO i = 1, trials
CALL RANDOM_NUMBER(rnum)
DO j = 1, 8
IF (rnum < mapping(j)) THEN
probcount(j) = probcount(j) + 1
EXIT
END IF
END DO
END DO
WRITE(*, "(A,I10)") "Trials: ", trials
WRITE(*, "(A,8A10)") "Items: ", items
WRITE(*, "(A,8F10.6)") "Target Probability: ", expected
WRITE(*, "(A,8F10.6)") "Attained Probability:", REAL(probcount) / REAL(trials)
ENDPROGRAM PROBS
You may also check:How to resolve the algorithm Scope modifiers step by step in the 68000 Assembly programming language
You may also check:How to resolve the algorithm Pick random element step by step in the jq programming language
You may also check:How to resolve the algorithm Grayscale image step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Earliest difference between prime gaps step by step in the Pascal programming language
You may also check:How to resolve the algorithm Shoelace formula for polygonal area step by step in the Kotlin programming language