How to resolve the algorithm Unbias a random generator step by step in the Wren programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Unbias a random generator step by step in the Wren programming language

Table of Contents

Problem Statement

The actual unbiasing should be done by generating two numbers at a time from randN and only returning a 1 or 0 if they are different. As long as you always return the first number or always return the second number, the probabilities discussed above should take over the biased probability of randN. This task is an implementation of Von Neumann debiasing, first described in a 1951 paper.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Unbias a random generator step by step in the Wren programming language

Source code in the wren programming language

import "random" for Random
import "/fmt" for Fmt

var rand = Random.new()

var biased = Fn.new { |n| rand.float() < 1 / n }

var unbiased = Fn.new { |n|
    while (true) {
        var a = biased.call(n)
        var b = biased.call(n)
        if (a != b) return a
    }
}

var m = 50000
var f = "$d: $2.2f\%  $2.2f\%"
for (n in 3..6) {
    var c1 = 0
    var c2 = 0
    for (i in 0...m) {
        if (biased.call(n)) c1 = c1 + 1
        if (unbiased.call(n)) c2 = c2 + 1
    }
    Fmt.print(f, n, 100 * c1 / m, 100 * c2 / m)
}

  

You may also check:How to resolve the algorithm Read entire file step by step in the 11l programming language
You may also check:How to resolve the algorithm Sorting algorithms/Bubble sort step by step in the ooRexx programming language
You may also check:How to resolve the algorithm N-queens problem step by step in the Nim programming language
You may also check:How to resolve the algorithm Chinese zodiac step by step in the Nim programming language
You may also check:How to resolve the algorithm Dinesman's multiple-dwelling problem step by step in the Haskell programming language