Probabilistic choice: Difference between revisions

m
syntax highlighting fixup automation
(Probabilistic choice in Yabasic)
m (syntax highlighting fixup automation)
Line 19:
 
=={{header|Ada}}==
<langsyntaxhighlight lang="ada">with Ada.Numerics.Float_Random; use Ada.Numerics.Float_Random;
with Ada.Text_IO; use Ada.Text_IO;
 
Line 52:
end if;
end loop;
end Random_Distribution;</langsyntaxhighlight>
Sample output:
<pre>
Line 72:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny]}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of FORMATted transput}}
<langsyntaxhighlight lang="algol68">INT trials = 1 000 000;
 
MODE LREAL = LONG REAL;
Line 143:
FOR i FROM LWB items TO UPB items DO printf(($f(real repr)" "$, prob count OF items[i]/trials)) OD;
printf($l$)
)</langsyntaxhighlight>
Sample output:
<pre>
Line 155:
AppleScript does have a <tt>random number</tt> command, but this is located in the StandardAdditions OSAX and invoking it a million times can take quite a while. Since Mac OS X 10.11, it's been possible to use the randomising features of the system's "GameplayKit" framework, which are faster to access.
 
<langsyntaxhighlight lang="applescript">use AppleScript version "2.5" -- Mac OS X 10.11 (El Capitan) or later.
use framework "Foundation"
use framework "GameplayKit"
Line 216:
end task
 
task()</langsyntaxhighlight>
 
{{output}}
<langsyntaxhighlight lang="applescript">"{ ¬
{|item|:aleph, probability:0.2, actual:0.20033}, ¬
{|item|:beth, probability:0.166666666667, actual:0.166744}, ¬
Line 228:
{|item|:zayin, probability:0.090909090909, actual:0.090721}, ¬
{|item|:heth, probability:0.063455988456, actual:0.063817} ¬
}"</langsyntaxhighlight>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">nofTrials: 10000
probabilities: #[
aleph: to :rational [1 5]
Line 281:
pad to :string to :floating s2 10
pad to :string s1 10
]</langsyntaxhighlight>
 
{{out}}
Line 300:
=={{header|AutoHotkey}}==
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276279.html#276279 forum]
<langsyntaxhighlight AutoHotkeylang="autohotkey">s1 := "aleph", p1 := 1/5.0 ; Input
s2 := "beth", p2 := 1/6.0
s3 := "gimel", p3 := 1/7.0
Line 338:
heth 0.063456 0.063342
---------------------------
*/</langsyntaxhighlight>
 
=={{header|AWK}}==
 
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
 
BEGIN {
Line 414:
counts[sym] = 0;
}
</syntaxhighlight>
</lang>
 
Example output:
Line 435:
=={{header|BASIC256}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight BASIC256lang="basic256">dim letters$ = {"aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"}
dim actual(8) fill 0 ## all zero by default
dim probs = {1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 0}
Line 485:
print " ", "--------", "--------"
print " ", ljust(sumActual,8,"0"), "1.000000"
end</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> DIM item$(7), prob(7), cnt%(7)
item$() = "aleph","beth","gimel","daleth","he","waw","zayin","heth"
prob() = 1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 1759/27720
Line 506:
FOR i% = 0 TO DIM(item$(),1)
PRINT item$(i%), cnt%(i%)/1E6, prob(i%)
NEXT</langsyntaxhighlight>
'''Output:'''
<pre>
Line 521:
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
Line 554:
 
return 0;
}</langsyntaxhighlight>output<syntaxhighlight lang="text"> Name Count Ratio Expected
aleph 199928 19.9928% 20.0000%
beth 166489 16.6489% 16.6667%
Line 562:
waw 99935 9.9935% 10.0000%
zayin 91001 9.1001% 9.0909%
heth 63330 6.3330% 6.3456%</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
Line 568:
{{trans|Java}}
 
<langsyntaxhighlight lang="csharp">
using System;
 
Line 640:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 650:
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <cstdlib>
#include <iostream>
#include <vector>
Line 701:
}
return 0 ;
}</langsyntaxhighlight>
Output:
<PRE>letter frequency attained frequency expected
Line 719:
It uses the language built-in (frequencies) to count the number of occurrences of each distinct name. Note that while we actually generate a sequence of num-trials random samples, the sequence is lazily generated and lazily consumed. This means that the program will scale to an arbitrarily-large num-trials with no ill effects, by throwing away elements it's already processed.
 
<langsyntaxhighlight Clojurelang="clojure">(defn to-cdf [pdf]
(reduce
(fn [acc n] (conj acc (+ (or (last acc) 0) n)))
Line 740:
(doseq [[idx exp] expected]
(println "Expected number of" (*names* idx) "was"
(* num-trials exp) "and actually got" (actual idx))))</langsyntaxhighlight>
 
<pre>Expected number of aleph was 200000.0 and actually got 199300
Line 754:
 
This is a straightforward, if a little verbose implementation based upon the Perl one.
<langsyntaxhighlight lang="lisp">(defvar *probabilities* '((aleph 1/5)
(beth 1/6)
(gimel 1/7)
Line 799:
WAW 0.100068 0.1
ZAYIN 0.090458 0.09090909
HETH 0.063481 0.06345599</langsyntaxhighlight>
 
=={{header|D}}==
===Basic Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.random, std.string, std.range;
 
Line 817:
foreach (name, p, co; zip(items, pr, counts[]))
writefln("%-7s %.8f %.8f", name, p, co / nTrials);
}</langsyntaxhighlight>
{{out}}
<pre>Item Target prob Attained prob
Line 830:
 
===A Faster Version===
<langsyntaxhighlight lang="d">void main() {
import std.stdio, std.random, std.algorithm, std.range;
 
Line 850:
foreach (name, p, co; zip(items, pr, counts[]))
writefln("%-7s %.8f %.8f", name, p, co / nTrials);
}</langsyntaxhighlight>
 
=={{header|E}}==
Line 858:
It is rather verbose, due to using the tree rather than a linear search, and having code to print the tree (which was used to debug it).
 
<langsyntaxhighlight lang="e">pragma.syntax("0.9")</langsyntaxhighlight>
 
First, the algorithm:
 
<langsyntaxhighlight lang="e">/** Makes leaves of the binary tree */
def leaf(value) {
return def leaf {
Line 916:
}
}
}</langsyntaxhighlight>
 
Then the test setup:
 
<langsyntaxhighlight lang="e">def rosetta := setupProbabilisticChoice(entropy, def probTable := [
"aleph" => 1/5,
"beth" => 1/6.0,
Line 941:
for item in probTable.domain() {
stdout.print(item, "\t", timesFound[item] / trials, "\t", probTable[item], "\n")
}</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Probabilistic do
@tries 1000000
@probs [aleph: 1/5,
Line 971:
end
 
Probabilistic.test</langsyntaxhighlight>
 
{{out}}
Line 990:
The optimized version of Java.
 
<langsyntaxhighlight lang="erlang">
-module(probabilistic_choice).
 
Line 1,022:
get_choice(T,Ran - Prob)
end.
</syntaxhighlight>
</lang>
 
Output:
Line 1,038:
 
=={{header|ERRE}}==
<langsyntaxhighlight ERRElang="erre">PROGRAM PROB_CHOICE
 
DIM ITEM$[7],PROB[7],CNT[7]
Line 1,072:
END FOR
END IF
END PROGRAM</langsyntaxhighlight>
 
Output:
Line 1,091:
=={{header|Euphoria}}==
{{trans|PureBasic}}
<langsyntaxhighlight lang="euphoria">constant MAX = #3FFFFFFF
constant times = 1e6
atom d,e
Line 1,123:
printf(1,"%-7s should be %f is %f | Deviatation %6.3f%%\n",
{Mapps[j][1],Mapps[j][2],d,(1-Mapps[j][2]/d)*100})
end for</langsyntaxhighlight>
 
Output:
Line 1,138:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: arrays assocs combinators.random io kernel macros math
math.statistics prettyprint quotations sequences sorting formatting ;
IN: rosettacode.proba
Line 1,174:
: example ( # data -- )
[ case-probas generate-normalized ]
[ summarize ] bi ; inline</langsyntaxhighlight>
 
In a REPL:
<syntaxhighlight lang="text">USE: rosettacode.proba
1000000 data example</langsyntaxhighlight>
outputs
<syntaxhighlight lang="text"> Key Value expected
heth: 0.063469 0.063456
waw: 0.100226 0.100000
Line 1,188:
he: 0.110562 0.111111
aleph: 0.199868 0.200000
gimel: 0.142961 0.142857</langsyntaxhighlight>
 
=={{header|Fermat}}==
<langsyntaxhighlight lang="fermat">
trials:=1000000;
 
Line 1,240:
 
!!('The various probabilities add up to ',Sigma<i=1,8>[count[i]/trials]); {check if our trials add to 1}
</syntaxhighlight>
</lang>
{{out}}<pre>
aleph 199939 / 1000000 differs from 1 / 5 by -61 / 1000000 or about one part in 16393
Line 1,262:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">include random.fs
 
\ common factors of desired probabilities (1/5 .. 1/11)
Line 1,305:
f- fabs fs. ;
 
: .results .header 8 0 do i .result loop ;</langsyntaxhighlight>
 
<pre>
Line 1,324:
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">PROGRAM PROBS
IMPLICIT NONE
Line 1,356:
WRITE(*, "(A,8F10.6)") "Attained Probability:", REAL(probcount) / REAL(trials)
ENDPROGRAM PROBS</langsyntaxhighlight>
Sample Output:
<pre>
Line 1,365:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Dim letters (0 To 7) As String = {"aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"}
Line 1,423:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,442:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,504:
}
fmt.Printf("Totals %8.6f %8.6f\n", totalTarget, totalGenerated)
}</langsyntaxhighlight>
Output:
<pre>
Line 1,520:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">import System.Random (newStdGen, randomRs)
dataBinCounts :: [Float] -> [Float] -> [Int]
Line 1,545:
["aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"]
expected
actual</langsyntaxhighlight>
{{Out}}
Sample
Line 1,559:
 
=={{header|HicEst}}==
<langsyntaxhighlight HicEstlang="hicest">REAL :: trials=1E6, n=8, map(n), limit(n), expected(n), outcome(n)
 
expected = 1 / ($ + 4)
Line 1,575:
outcome = outcome / trials
 
DLG(Text=expected, Text=outcome, Y=0) </langsyntaxhighlight>
Exported from the spreadsheet-like DLG function:
<pre>0.2 0.199908
Line 1,588:
=={{header|Icon}} and {{header|Unicon}}==
 
<syntaxhighlight lang="icon">
<lang Icon>
record Item(value, probability)
 
Line 1,639:
left(count(sample, item.value)/*sample, 6))
end
</syntaxhighlight>
</lang>
 
Output:
Line 1,654:
 
=={{header|J}}==
<syntaxhighlight lang="j">
<lang J>
main=: verb define
hdr=. ' target actual '
Line 1,671:
da (distribution of actual values among partitions)
pa (actual proportions)
)</langsyntaxhighlight>
Example use:
<langsyntaxhighlight lang="j">main 1e6
target actual
aleph 0.200000 0.200344
Line 1,682:
waw 0.100000 0.099751
zayin 0.090909 0.091121
heth 0.063456 0.063527</langsyntaxhighlight>
Note that there is no rounding error in summing the proportions, as they are represented as rational numbers, not floating-point approximations.
<langsyntaxhighlight Jlang="j"> pt=. (, 1-+/)1r1%5+i.7
pt
1r5 1r6 1r7 1r8 1r9 1r10 1r11 1759r27720
+/pt
1</langsyntaxhighlight>
 
=={{header|Java}}==
{{trans|C}}
<langsyntaxhighlight lang="java">public class Prob{
static long TRIALS= 1000000;
 
Line 1,758:
 
}
}</langsyntaxhighlight>
Output:
<pre>Trials: 1000000
Line 1,765:
Attained prob.: 0.199615 0.167517 0.142612 0.125211 0.110970 0.099614 0.091002 0.063459 </pre>
{{works with|Java|1.5+}}
<langsyntaxhighlight lang="java5">import java.util.EnumMap;
 
public class Prob {
Line 1,816:
return null;
}
}</langsyntaxhighlight>
Output:
<pre>Target probabliities: {ALEPH=0.2, BETH=0.16666666666666666, GIMEL=0.14285714285714285, DALETH=0.125, HE=0.1111111111111111, WAW=0.1, ZAYIN=0.09090909090909091, HETH=0.06345598845598846}
Line 1,824:
===ES5===
Fortunately, iterating over properties added to an object maintains the insertion order.
<langsyntaxhighlight lang="javascript">var probabilities = {
aleph: 1/5.0,
beth: 1/6.0,
Line 1,855:
for (var name in probabilities)
// using WSH
WScript.Echo(name + "\t" + probabilities[name] + "\t" + randomly[name]/iterations);</langsyntaxhighlight>
output:
<pre>aleph 0.2 0.200597
Line 1,869:
By functional composition:
{{Trans|Haskell}}
<langsyntaxhighlight JavaScriptlang="javascript">(() => {
'use strict';
 
Line 1,974:
.map(unwords)
.join('\n');
})();</langsyntaxhighlight>
{{Out}}
Sample:
Line 1,989:
=={{header|Julia}}==
I made the solution to this task more difficult than I had anticipated by using the Hebrew characters (rather than their anglicised names) as labels for the sampled collection of objects. In doing so, I encountered an interesting subtlety of bidirectional text in Unicode. Namely, that strong right-to-left characters, such as those of Hebrew, override the directionality of European digits, which have weak directionality. Because of this property of Unicode, my table of items and yields had its lines of data interpreted as if it were entirely Hebrew and output in reverse order (from my English speaking perspective). I was able to get the table to display as I liked on my terminal by preceding the the Hebrew characters by the Unicode RLI (right-to-left isolate) control character (<tt>U+2067</tt>). However, when I pasted this output into this Rosetta Code entry, the display reverted to the "backwards" version. Rather than continue the struggle, trying to force this entry to display as it does on my terminal, I created an alternative version of the table. This "Displayable Here" table adds "yields" to to each line, and this strong left-to-right text makes the whole line display as left-to-right (without the need for a RLI characer).
<langsyntaxhighlight Julialang="julia">using Printf
 
p = [1/i for i in 5:11]
Line 2,020:
plab[i], accum[i], p[i], r[i]))
end
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,056:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">// version 1.0.6
 
fun main(args: Array<String>) {
Line 2,093:
println("\t-------- --------")
println("\t${"%8.6f".format(sumActual)} 1.000000")
}</langsyntaxhighlight>
 
{{out}}
Line 2,112:
 
=={{header|Liberty BASIC}}==
<syntaxhighlight lang="lb">
<lang lb>
names$="aleph beth gimel daleth he waw zayin heth"
dim sum(8)
Line 2,137:
print word$(names$, i), using( "#.#####", counter(i) /N), using( "#.#####", 1/(i+4))
next
</syntaxhighlight>
</lang>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">items = {}
items["aleph"] = 1/5.0
items["beth"] = 1/6.0
Line 2,173:
for item, _ in pairs( items ) do
print( item, samples[item]/num_trials, items[item] )
end</langsyntaxhighlight>
Output
<pre>gimel 0.142606 0.14285714285714
Line 2,186:
=={{header|Mathematica}}/{{header|Wolfram Language}}==
Built-in function can already do a weighted random choosing. Example for making a million random choices would be:
<langsyntaxhighlight Mathematicalang="mathematica">choices={{"aleph", 1/5},{"beth", 1/6},{"gimel", 1/7},{"daleth", 1/8},{"he", 1/9},{"waw", 1/10},{"zayin", 1/11},{"heth", 1759/27720}};
data=RandomChoice[choices[[All,2]]->choices[[All,1]],10^6];</langsyntaxhighlight>
To compare the data we use the following code to make a table:
<langsyntaxhighlight Mathematicalang="mathematica">Grid[{#[[1]],N[Count[data,#[[1]]]/10^6],N[#[[2]]]}&/@choices]</langsyntaxhighlight>
gives back (item, attained prob., target prob.):
<pre>aleph 0.200036 0.2
Line 2,202:
=={{header|MATLAB}}==
{{works with|MATLAB|with Statistics Toolbox}}
<langsyntaxhighlight MATLABlang="matlab">function probChoice
choices = {'aleph' 'beth' 'gimel' 'daleth' 'he' 'waw' 'zayin' 'heth'};
w = [1/5 1/6 1/7 1/8 1/9 1/10 1/11 1759/27720];
Line 2,212:
choices{k}, T(k, 2), T(k, 3), 100*w(k))
end
end</langsyntaxhighlight>
{{out}}
<pre>Value Count Percent Goal
Line 2,224:
heth 63171 6.32% 6.35%</pre>
{{works with|MATLAB|without toolboxes}}
<langsyntaxhighlight MATLABlang="matlab">function probChoice
choices = {'aleph' 'beth' 'gimel' 'daleth' 'he' 'waw' 'zayin' 'heth'};
w = [1/5 1/6 1/7 1/8 1/9 1/10 1/11 1759/27720];
Line 2,240:
choices{k}, results(k), 100*results(k)/nSamp, 100*w(k))
end
end</langsyntaxhighlight>
{{out}}
<pre>Value Count Percent Goal
Line 2,253:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import tables, random, strformat, times
 
var start = cpuTime()
Line 2,286:
echo "====== ======== ======== "
echo &"Total: {s2:^8.2f} {s1:^8.2f}"
echo &"\nExecution time: {cpuTime()-start:.2f} s"</langsyntaxhighlight>
 
{{out}}
Line 2,306:
=={{header|OCaml}}==
 
<langsyntaxhighlight lang="ocaml">let p = [
"Aleph", 1.0 /. 5.0;
"Beth", 1.0 /. 6.0;
Line 2,335:
let d = Hashtbl.find h v in
Printf.printf "%s \t %f %f\n" v p (float d /. float n)
) p</langsyntaxhighlight>
 
Output:
Line 2,348:
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">pc()={
my(v=[5544,10164,14124,17589,20669,23441,25961,27720],u=vector(8),e);
for(i=1,1e6,
Line 2,361:
print("Diff: ",u-e);
print("StDev: ",vector(8,i,sqrt(abs(u[i]-v[i])/e[i])));
};</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use List::Util qw(first sum);
use constant TRIALS => 1e6;
 
Line 2,401:
$_, $results{$_}/TRIALS, $ps{$_},
abs($results{$_}/TRIALS - $ps{$_});
}</langsyntaxhighlight>
 
Sample output:
Line 2,416:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">lim</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1000000</span><span style="color: #0000FF;">,</span>
Line 2,443:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%6s %8.6f %8.6f\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">names</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">],</span><span style="color: #000000;">results</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]/</span><span style="color: #000000;">lim</span><span style="color: #0000FF;">,</span><span style="color: #000000;">probs</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">]})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 2,458:
 
=={{header|Phixmonti}}==
<langsyntaxhighlight Phixmontilang="phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/Probabilistic_choice
by Galileo, 05/2022 #/
 
Line 2,486:
pop swap
1 get "\t" rot 3 get trial / "\t" rot 2 get nip "\n" 6 tolist lprint
endfor</langsyntaxhighlight>
{{out}}
<pre>item actual theoretical
Line 2,502:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(let (Count 1000000 Denom 27720 N Denom)
(let Probs
(mapcar
Line 2,518:
(cdddr X)
(format (cadr X) 6)
(format (caddr X) 6) ) ) ) ) )</langsyntaxhighlight>
Output:
<pre> Probability Result
Line 2,531:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli"> probch: Proc Options(main);
Dcl prob(8) Dec Float(15) Init((1/5.0), /* aleph */
(1/6.0), /* beth */
Line 2,575:
Put Edit(what(i),cnt(i),pr,prob(i))(Skip,a,f(10),x(2),2(f(11,8)));
End;
End;</langsyntaxhighlight>
{{out}}
<pre>One million trials
Line 2,604:
{{trans|Java Script}}
The guts of this script are translated from the Java Script entry. Then I stole the idea to show the actual Hebrew character from Julia.
<syntaxhighlight lang="powershell">
<lang PowerShell>
$character = [PSCustomObject]@{
aleph = [PSCustomObject]@{Expected=1/5 ; Alpha="א"}
Line 2,651:
}
}
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 2,667:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">#times=1000000
 
Structure Item
Line 2,708:
Print(#CRLF$+"Press ENTER to exit"):Input()
CloseConsole()
EndIf</langsyntaxhighlight>
 
Output may look like
Line 2,726:
=={{header|Python}}==
Two different algorithms are coded.
<langsyntaxhighlight lang="python">import random, bisect
 
def probchoice(items, probs):
Line 2,789:
probs[-1] = 1-sum(probs[:-1])
tester(probchoice, items, probs, 1000000)
tester(probchoice2, items, probs, 1000000)</langsyntaxhighlight>
 
Sample output:
Line 2,813:
Uses point$ from the bignum rational arithmetic module bigrat.qky. <code>10 point$</code> returns a ratio as a decimal string accurate to 10 decimal places with round-to-nearest on the final digit.
 
<langsyntaxhighlight Quackerylang="quackery"> [ $ "bigrat.qky" loadfile ] now!
 
( --------------- zen object orientation -------------- )
Line 2,884:
drop ]
 
witheach [ report swap do ]</langsyntaxhighlight>
 
{{out}}
Line 2,921:
 
=={{header|R}}==
<langsyntaxhighlight Rlang="r">prob = c(aleph=1/5, beth=1/6, gimel=1/7, daleth=1/8, he=1/9, waw=1/10, zayin=1/11, heth=1759/27720)
# Note that R doesn't actually require the weights
# vector for rmultinom to sum to 1.
Line 2,928:
Requested = prob,
Obtained = hebrew/sum(hebrew))
print(d)</langsyntaxhighlight>
 
Sample output:
Line 2,942:
 
A histogram of the data is also possible using, for example,
<langsyntaxhighlight Rlang="r">library(ggplot2)
qplot(factor(names(prob), levels = names(prob)), hebrew, geom = "histogram")</langsyntaxhighlight>
 
=={{header|Racket}}==
Line 2,954:
as a module. Either run the program in DrRacket or run `raco test prob-choice.rkt`
 
<langsyntaxhighlight lang="racket">#lang racket
;;; returns a probabalistic choice from the sequence choices
;;; choices generates two values -- the chosen value and a
Line 3,040:
(test-p-c-function probabalistic-choice/exact test-weightings/50:50)
(test-p-c-function probabalistic-choice test-weightings/rosetta)
(test-p-c-function probabalistic-choice/exact test-weightings/rosetta))</langsyntaxhighlight>
Output (note that the progress counts, which go to standard error, are
interleaved with the output on standard out)
Line 3,075:
(formerly Perl 6)
{{works with|Rakudo|2018.10}}
<syntaxhighlight lang="raku" perl6line>constant TRIALS = 1e6;
constant @event = <aleph beth gimel daleth he waw zayin heth>;
Line 3,093:
$expected,
abs $occurred - $expected;
}</langsyntaxhighlight>
{{out}}
<pre>Event Occurred Expected Difference
Line 3,106:
 
=={{header|ReScript}}==
<langsyntaxhighlight lang="rescript">let p = [
("Aleph", 1.0 /. 5.0),
("Beth", 1.0 /. 6.0),
Line 3,148:
}
)
}</langsyntaxhighlight>
{{output}}
<pre>
Line 3,166:
 
A little extra REXX code was added to provide head and foot titles along with the totals.
<langsyntaxhighlight lang="rexx">/*REXX program displays results of probabilistic choices, gen random #s per probability.*/
parse arg trials digs seed . /*obtain the optional arguments from CL*/
if trials=='' | trials=="," then trials= +1e6 /*Not specified? Then use the default.*/
Line 3,197:
left( format( @.cell/trials * 100, d), w-2) /* [↓] foot title. [↓] */
if cell==# then say center(_,15,_) center(_,d,_) center(_,w,_) center(_,w,_)
end /*c*/ /*stick a fork in it, we are all done.*/</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input:}}
<pre>
Line 3,214:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Probabilistic choice
 
Line 3,237:
see "" + item[i] + " " + cnt[i]/1000000 + " " + prob[i] + nl
next
</syntaxhighlight>
</lang>
Output:
<pre>
Line 3,252:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">probabilities = {
"aleph" => 1/5.0,
"beth" => 1/6.0,
Line 3,288:
val = probabilities[k]
printf "%-8s%.8f %.8f %6.3f %%\n", k, val, act, 100*(act-val)/val
end</langsyntaxhighlight>
 
{{out}}
Line 3,304:
 
=={{header|Rust}}==
<langsyntaxhighlight Rustlang="rust">extern crate rand;
 
use rand::distributions::{IndependentSample, Sample, Weighted, WeightedChoice};
Line 3,430:
let counts = take_samples(&mut rng, &wc);
print_mapping(&counts);
}</langsyntaxhighlight>
{{out}}
<pre> ~~~ U32 METHOD ~~~
Line 3,458:
=={{header|Scala}}==
This algorithm consists of a concise two-line tail-recursive loop (<tt>def weighted</tt>). The rest of the code is for API robustness, testing and display. <tt>weightedProb</tt> is for the task as stated (0 < <i>p</i> < 1), and <tt>weightedFreq</tt> is the equivalent based on integer frequencies (<i>f</i> >= 0).
<langsyntaxhighlight Scalalang="scala">object ProbabilisticChoice extends App {
import scala.collection.mutable.LinkedHashMap
 
Line 3,521:
println("Checking weighted frequencies:")
check(frequencies.map{case (a, b) => a -> b.toDouble}, for (i <- 1 to 1000000) yield weightedFreq(frequencies))
}</langsyntaxhighlight>
{{out}}
<pre>Checking weighted probabilities:
Line 3,549:
Using guile scheme 2.0.11.
 
<langsyntaxhighlight lang="scheme">(use-modules (ice-9 format))
 
(define (random-choice probs)
Line 3,593:
(he 1/9) (waw 1/10) (zayin 1/11) (heth 1759/27720)))
 
(format-results probs (choices 1000000 probs))</langsyntaxhighlight>
 
Example output:
Line 3,608:
=={{header|Seed7}}==
To reduce the runtime this program should be compiled.
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 3,652:
100.0 * flt(table[aLetter]) / 27720.0 digits 4 lpad 8 <& "%");
end for;
end func;</langsyntaxhighlight>
 
Outout:
Line 3,669:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">define TRIALS = 1e4;
 
func prob_choice_picker(options) {
Line 3,709:
abs(v/TRIALS - ps{k})
);
}</langsyntaxhighlight>
 
{{out}}
Line 3,725:
 
=={{header|Stata}}==
<langsyntaxhighlight lang="stata">clear
mata
letters="aleph","beth","gimel","daleth","he","waw","zayin","heth"
Line 3,732:
st_addvar("str10","a")
st_sstore(.,.,a)
end</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
set map [dict create]
Line 3,771:
]
}
}</langsyntaxhighlight>
<pre>using 1000000 samples:
expected actual difference
Line 3,789:
implemented by the run time system.
 
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
#import flo
Line 3,806:
#show+
 
results = format simulation 1000000</langsyntaxhighlight>
output:
<pre>
Line 3,821:
=={{header|VBScript}}==
Derived from the BBC BASIC version
<syntaxhighlight lang="vb">
<lang vb>
item = Array("aleph","beth","gimel","daleth","he","waw","zayin","heth")
prob = Array(1/5.0, 1/6.0, 1/7.0, 1/8.0, 1/9.0, 1/10.0, 1/11.0, 1759/27720)
Line 3,853:
WScript.StdOut.Write item(i) & vbTab & FormatNumber(cnt(i)/1000000,6) & vbTab & FormatNumber(prob(i),6)
WScript.StdOut.WriteLine
Next</langsyntaxhighlight>
 
{{out}}
Line 3,871:
{{trans|Kotlin}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight lang="ecmascript">import "random" for Random
import "/fmt" for Fmt
 
Line 3,906:
}
System.print("\t-------- --------")
Fmt.print("\t$8.6f 1.000000", sumActual)</langsyntaxhighlight>
 
{{out}}
Line 3,926:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">include c:\cxpl\codes;
def Size = 10_000_000;
int Tbl(12+1);
Line 3,952:
");
RlOut(0, S0); RlOut(0, S1);
]</langsyntaxhighlight>
 
Output:
Line 3,969:
 
=={{header|Yabasic}}==
<langsyntaxhighlight lang="yabasic">dim letters$(7)
data "aleph", "beth", "gimel", "daleth", "he", "waw", "zayin", "heth"
letters$(0) = "aleph"
Line 4,023:
print " -------- --------"
print " ", sumActual using "#.######", tab$, "1.000000"
end</langsyntaxhighlight>
 
=={{header|zkl}}==
{{trans|C}}
<langsyntaxhighlight lang="zkl">var names=T("aleph", "beth", "gimel", "daleth",
"he", "waw", "zayin", "heth");
var ptable=T(5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0).apply('/.fp(1.0));
Line 4,048:
"%6s%7d %7.4f%% %7.4f%%".fmt(names[i], r[i], r[i]/M*100,
ptable[i]*100).println();
}</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits