Sleeping Beauty problem: Difference between revisions
m (→{{header|J}}) |
|||
(18 intermediate revisions by 10 users not shown) | |||
Line 35: | Line 35: | ||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="11l">F sleeping_beauty_experiment(repetitions) |
||
‘ |
‘ |
||
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see |
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see |
||
Line 61: | Line 61: | ||
V CREDENCE = sleeping_beauty_experiment(1'000'000) |
V CREDENCE = sleeping_beauty_experiment(1'000'000) |
||
print(‘Results of experiment: Sleeping Beauty should estimate a credence of: ’CREDENCE)</ |
print(‘Results of experiment: Sleeping Beauty should estimate a credence of: ’CREDENCE)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 68: | Line 68: | ||
Results of experiment: Sleeping Beauty should estimate a credence of: 0.332540916 |
Results of experiment: Sleeping Beauty should estimate a credence of: 0.332540916 |
||
</pre> |
</pre> |
||
=={{header|ALGOL 68}}== |
|||
{{Trans|Wren}} |
|||
In Algol 68, the generated random numbers are in the semi-open range [0.0..1.0). |
|||
<syntaxhighlight lang="algol68"> |
|||
BEGIN # sleeping beauty problem - translated from the Wren sample # |
|||
PROC sleeping beauty = ( INT reps )REAL: |
|||
BEGIN |
|||
INT wakings := 0, heads := 0; |
|||
FOR i TO reps DO |
|||
wakings +:= 1; |
|||
IF next random < 0.5 THEN # [0..0.5) = heads, [0.5..1.0) = tails say # |
|||
heads +:= 1 |
|||
ELSE |
|||
wakings +:= 1 |
|||
FI |
|||
OD; |
|||
print( ( "Wakings over ", whole( reps, 0 ), " repetitions = ", whole( wakings, 0 ), newline ) ); |
|||
( heads / wakings ) * 100 |
|||
END; # sleeping beauty # |
|||
REAL pc = sleeping beauty( 1 000 000 ); |
|||
print( ( "Percentage probability of heads on waking = ", fixed( pc, -10, 6 ), "%", newline ) ) |
|||
END |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Wakings over 1000000 repetitions = 1499978 |
|||
Percentage probability of heads on waking = 33.335289%</pre> |
|||
=={{header|Arturo}}== |
=={{header|Arturo}}== |
||
Line 73: | Line 102: | ||
{{trans|Wren}} |
{{trans|Wren}} |
||
< |
<syntaxhighlight lang="rebol">sleepingBeauty: function [reps][ |
||
wakings: 0 |
wakings: 0 |
||
heads: 0 |
heads: 0 |
||
Line 87: | Line 116: | ||
pc: sleepingBeauty 100000 |
pc: sleepingBeauty 100000 |
||
print ["Percentage probability of heads on waking =" pc "%"]</ |
print ["Percentage probability of heads on waking =" pc "%"]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 97: | Line 126: | ||
==={{header|BASIC256}}=== |
==={{header|BASIC256}}=== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
<syntaxhighlight lang="basic256"> |
|||
<lang BASIC256> |
|||
iteraciones = 1000000 |
iteraciones = 1000000 |
||
cara = 0 |
cara = 0 |
||
Line 115: | Line 144: | ||
print "Percentage probability of heads on waking = "; (cara/dormir*100); "%" |
print "Percentage probability of heads on waking = "; (cara/dormir*100); "%" |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 122: | Line 151: | ||
==={{header|FreeBASIC}}=== |
==={{header|FreeBASIC}}=== |
||
< |
<syntaxhighlight lang="freebasic"> |
||
Const iteraciones = 1000000 |
Const iteraciones = 1000000 |
||
Randomize Timer |
Randomize Timer |
||
Line 136: | Line 165: | ||
Print using "Percentage probability of heads on waking = ###.######%"; (cara/dormir*100)'; "%" |
Print using "Percentage probability of heads on waking = ###.######%"; (cara/dormir*100)'; "%" |
||
Sleep |
Sleep |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 145: | Line 174: | ||
==={{header|GW-BASIC}}=== |
==={{header|GW-BASIC}}=== |
||
In this simulation, Sleeping Beauty flips a coin of her own. |
In this simulation, Sleeping Beauty flips a coin of her own. |
||
< |
<syntaxhighlight lang="gwbasic">10 RANDOMIZE TIMER |
||
20 MONDAY = 0 : TUESDAY = 1 |
20 MONDAY = 0 : TUESDAY = 1 |
||
30 HEADS = 0 : TAILS = 1 |
30 HEADS = 0 : TAILS = 1 |
||
Line 171: | Line 200: | ||
250 IF GUESS = HEADS THEN WHEADS = WHEADS + 1 ELSE CTAILS = CTAILS + 1 |
250 IF GUESS = HEADS THEN WHEADS = WHEADS + 1 ELSE CTAILS = CTAILS + 1 |
||
260 NEXT DAY |
260 NEXT DAY |
||
270 RETURN</ |
270 RETURN</syntaxhighlight> |
||
{{out}}<pre> |
{{out}}<pre> |
||
Sleeping Beauty was put through this experiment 300000 times. |
Sleeping Beauty was put through this experiment 300000 times. |
||
Line 183: | Line 212: | ||
==={{header|Yabasic}}=== |
==={{header|Yabasic}}=== |
||
{{trans|FreeBASIC}} |
{{trans|FreeBASIC}} |
||
<syntaxhighlight lang="yabasic"> |
|||
<lang Yabasic> |
|||
iteraciones = 1000000 |
iteraciones = 1000000 |
||
cara = 0 |
cara = 0 |
||
Line 197: | Line 226: | ||
print "Percentage probability of heads on waking = ", (cara/dormir*100), "%" |
print "Percentage probability of heads on waking = ", (cara/dormir*100), "%" |
||
end |
end |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 204: | Line 233: | ||
=={{header|C++}}== |
=={{header|C++}}== |
||
< |
<syntaxhighlight lang="cpp">#include <iostream> |
||
#include <random> |
#include <random> |
||
Line 229: | Line 258: | ||
std::cout << "Sleeping Beauty should estimate a credence of: " |
std::cout << "Sleeping Beauty should estimate a credence of: " |
||
<< double(heads) / wakenings << '\n'; |
<< double(heads) / wakenings << '\n'; |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 238: | Line 267: | ||
=={{header|CLU}}== |
=={{header|CLU}}== |
||
< |
<syntaxhighlight lang="clu">% This program needs to be merged with PCLU's "misc" library |
||
% to use the random number generator. |
% to use the random number generator. |
||
Line 288: | Line 317: | ||
chance: real := experiment$run(N) |
chance: real := experiment$run(N) |
||
stream$putl(po, f_form(chance, 1, 6)) |
stream$putl(po, f_form(chance, 1, 6)) |
||
end start_up </ |
end start_up </syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Chance of waking up with heads: 0.333758</pre> |
<pre>Chance of waking up with heads: 0.333758</pre> |
||
Line 295: | Line 324: | ||
{{trans|Swift}} |
{{trans|Swift}} |
||
< |
<syntaxhighlight lang="dyalect">let experiments = 10000 |
||
var heads = 0 |
var heads = 0 |
||
var wakenings = 0 |
var wakenings = 0 |
||
Line 306: | Line 335: | ||
} |
} |
||
print("Wakenings over \(experiments) experiments: \(wakenings)") |
print("Wakenings over \(experiments) experiments: \(wakenings)") |
||
print("Sleeping Beauty should estimate a credence of: \(Float(heads) / Float(wakenings))")</ |
print("Sleeping Beauty should estimate a credence of: \(Float(heads) / Float(wakenings))")</syntaxhighlight> |
||
=={{header|EasyLang}}== |
|||
<syntaxhighlight> |
|||
reps = 1e6 |
|||
for i to reps |
|||
coin = randint 2 |
|||
wakings += 1 |
|||
if coin = 1 |
|||
heads += 1 |
|||
else |
|||
wakings += 1 |
|||
. |
|||
. |
|||
print "Chance of waking up with heads: " & heads / wakings * 100 & "%" |
|||
</syntaxhighlight> |
|||
=={{header|Excel}}== |
=={{header|Excel}}== |
||
Line 316: | Line 360: | ||
{{Works with | Office 365 betas 2021}} |
{{Works with | Office 365 betas 2021}} |
||
< |
<syntaxhighlight lang="lisp">SLEEPINGB |
||
=LAMBDA(n, |
=LAMBDA(n, |
||
LET( |
LET( |
||
Line 333: | Line 377: | ||
) |
) |
||
) |
) |
||
)</ |
)</syntaxhighlight> |
||
{{Out}} |
{{Out}} |
||
Line 367: | Line 411: | ||
=={{header|F_Sharp|F#}}== |
=={{header|F_Sharp|F#}}== |
||
< |
<syntaxhighlight lang="fsharp"> |
||
// Sleeping Beauty: Nigel Galloway. May 16th., 2021 |
// Sleeping Beauty: Nigel Galloway. May 16th., 2021 |
||
let heads,woken=let n=System.Random() in {1..1000}|>Seq.fold(fun(h,w) g->match n.Next(2) with 0->(h+1,w+1) |_->(h,w+2))(0,0) |
let heads,woken=let n=System.Random() in {1..1000}|>Seq.fold(fun(h,w) g->match n.Next(2) with 0->(h+1,w+1) |_->(h,w+2))(0,0) |
||
printfn "During 1000 tosses Sleeping Beauty woke %d times, %d times the toss was heads. %.0f%% of times heads had been tossed when she awoke" woken heads (100.0*float(heads)/float(woken)) |
printfn "During 1000 tosses Sleeping Beauty woke %d times, %d times the toss was heads. %.0f%% of times heads had been tossed when she awoke" woken heads (100.0*float(heads)/float(woken)) |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 378: | Line 422: | ||
=={{header|Factor}}== |
=={{header|Factor}}== |
||
{{works with|Factor|0.99 2021-02-05}} |
{{works with|Factor|0.99 2021-02-05}} |
||
< |
<syntaxhighlight lang="factor">USING: combinators.random io kernel math prettyprint ; |
||
: sleeping ( n -- heads wakenings ) |
: sleeping ( n -- heads wakenings ) |
||
Line 385: | Line 429: | ||
"Wakenings over 1,000,000 experiments: " write |
"Wakenings over 1,000,000 experiments: " write |
||
1e6 sleeping dup . /f |
1e6 sleeping dup . /f |
||
"Sleeping Beauty should estimate a credence of: " write .</ |
"Sleeping Beauty should estimate a credence of: " write .</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Wakenings over 1,000,000 experiments: 1500127 |
Wakenings over 1,000,000 experiments: 1500127 |
||
Sleeping Beauty should estimate a credence of: 0.3332204540015612 |
Sleeping Beauty should estimate a credence of: 0.3332204540015612 |
||
</pre> |
|||
=={{header|Fortran}}== |
|||
{{trans|Go}} |
|||
Uses random_number from the Fortran 95 standard. |
|||
<syntaxhighlight lang="fortran"> |
|||
program sleepingbeauty |
|||
implicit none |
|||
integer :: total_reps |
|||
integer :: result_wakings |
|||
real :: result_percent |
|||
total_reps = 1e6 |
|||
call sleepingOp(total_reps, result_wakings, result_percent) |
|||
print *, "wakings over", total_reps, "reps: ", result_wakings |
|||
print *, "percentage probability of heads on wake:", result_percent |
|||
contains |
|||
subroutine sleepingOp(reps, wakings, percent) |
|||
integer, intent(in) :: reps |
|||
integer, intent(out) :: wakings |
|||
real, intent(out) :: percent |
|||
integer :: heads |
|||
integer :: i |
|||
real :: coin |
|||
wakings = 0 |
|||
heads = 0 |
|||
do i = 0, reps, 1 |
|||
call random_number(coin) |
|||
wakings = wakings + 1 |
|||
if (coin > 0.5) then |
|||
heads = heads + 1 |
|||
else |
|||
wakings = wakings + 1 |
|||
end if |
|||
end do |
|||
percent = real(heads) / real(wakings) |
|||
end subroutine sleepingOp |
|||
end program sleepingbeauty |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
wakings over 1000000 reps: 1500326 |
|||
percentage probability of heads on wake: 0.333044946 |
|||
</pre> |
|||
=={{header|FutureBasic}}== |
|||
<syntaxhighlight lang="futurebasic"> |
|||
_iterations = 1000000 |
|||
local fn SleepingBeauty |
|||
NSUInteger i |
|||
CGFloat heads = 0, sleep = 0 |
|||
for i = 1 to _iterations |
|||
NSInteger coinToss = int( rnd(2) ) |
|||
sleep++ |
|||
if coinToss = 1 then heads++ else sleep++ |
|||
next |
|||
printf @"Awakenings over %lld sleep cycles = %.f", _iterations, sleep |
|||
printf @"Percent probability of heads on waking = %.4f%%", heads / sleep * 100 |
|||
end fn |
|||
randomize |
|||
fn SleepingBeauty |
|||
HandleEvents |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
Awakenings over 1000000 sleep cycles = 1499725 |
|||
Percent probability of heads on waking = 33.3578% |
|||
</pre> |
</pre> |
||
Line 395: | Line 523: | ||
{{trans|Wren}} |
{{trans|Wren}} |
||
{{libheader|Go-rcu}} |
{{libheader|Go-rcu}} |
||
< |
<syntaxhighlight lang="go">package main |
||
import ( |
import ( |
||
Line 424: | Line 552: | ||
pc := sleepingBeauty(1e6) |
pc := sleepingBeauty(1e6) |
||
fmt.Printf("Percentage probability of heads on waking = %f%%\n", pc) |
fmt.Printf("Percentage probability of heads on waking = %f%%\n", pc) |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 434: | Line 562: | ||
=={{header|Haskell}}== |
=={{header|Haskell}}== |
||
< |
<syntaxhighlight lang="haskell">import Data.Monoid (Sum(..)) |
||
import System.Random (randomIO) |
import System.Random (randomIO) |
||
import Control.Monad (replicateM) |
import Control.Monad (replicateM) |
||
Line 454: | Line 582: | ||
let (Sum w, Sum h) = foldMap anExperiment tosses |
let (Sum w, Sum h) = foldMap anExperiment tosses |
||
let ratio = fromIntegral h / fromIntegral w |
let ratio = fromIntegral h / fromIntegral w |
||
putStrLn $ "Ratio: " ++ show ratio</ |
putStrLn $ "Ratio: " ++ show ratio</syntaxhighlight> |
||
<pre>*Main> main |
<pre>*Main> main |
||
Line 461: | Line 589: | ||
=={{header|J}}== |
=={{header|J}}== |
||
Simulation code: |
Simulation code: |
||
< |
<syntaxhighlight lang="j">sb=: {{ |
||
monday=. ?2 |
monday=. ?2 |
||
if. -. monday do. |
if. -. monday do. |
||
Line 469: | Line 597: | ||
<monday |
<monday |
||
end. |
end. |
||
}}</ |
}}</syntaxhighlight> |
||
Results:< |
Results:<syntaxhighlight lang="j"> sample=: sb"0 i.1e6 NB. simulate a million mondays |
||
#sample NB. number of experiments |
#sample NB. number of experiments |
||
1000000 |
1000000 |
||
Line 483: | Line 611: | ||
0.4996 |
0.4996 |
||
sample+&#;sample NB. total number of awakenings |
sample+&#;sample NB. total number of awakenings |
||
2500433</ |
2500433</syntaxhighlight> |
||
It's probably worth noting here that the number of heads divided by the number of awakenings would be about 0.3 -- but Sleeping Beauty was not asked to guess whether the coin was heads on Wednesday. |
It's probably worth noting here that the number of heads divided by the number of awakenings would be about 0.3 -- but Sleeping Beauty was not asked to guess whether the coin was heads on Wednesday. |
||
=={{header|Java}}== |
|||
<syntaxhighlight lang="java"> |
|||
import java.util.concurrent.ThreadLocalRandom; |
|||
public final class SleepingBeauty { |
|||
public static void main(String[] aArgs) { |
|||
final int experiments = 1_000_000; |
|||
ThreadLocalRandom random = ThreadLocalRandom.current(); |
|||
enum Coin { HEADS, TAILS } |
|||
int heads = 0; |
|||
int awakenings = 0; |
|||
for ( int i = 0; i < experiments; i++ ) { |
|||
Coin coin = Coin.values()[random.nextInt(0, 2)]; |
|||
switch ( coin ) { |
|||
case HEADS -> { awakenings += 1; heads += 1; } |
|||
case TAILS -> awakenings += 2; |
|||
} |
|||
} |
|||
System.out.println("Awakenings over " + experiments + " experiments: " + awakenings); |
|||
String credence = String.format("%.3f", (double) heads / awakenings); |
|||
System.out.println("Sleeping Beauty should estimate a credence of: " + credence); |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{ out }} |
|||
<pre> |
|||
Awakenings over 1000000 experiments: 1499522 |
|||
Sleeping Beauty should estimate a credence of: 0.334 |
|||
</pre> |
|||
=={{header|jq}}== |
|||
'''Adapted from [[#Wren|Wren]]''' |
|||
'''Works with jq, the C implementation of jq''' |
|||
'''Works with gojq, the Go implementation of jq''' |
|||
'''Works with jaq, the Rust implementation of jq''' |
|||
Since jq does not currently have a built-in PRNG, |
|||
/dev/random will be used as a source of entropy. An invocation |
|||
of jq along the lines of the following would be appropriate |
|||
in a typical command-line environment: |
|||
<pre> |
|||
< /dev/random tr -cd '0-9' | fold -w 1 | jq -cnr -f sleeping.jq |
|||
</pre> |
|||
where "sleeping.jq" is the name of a file containing the following jq program. |
|||
<syntaxhighlight lang="jq"> |
|||
# Output: a PRN in range(0; .) |
|||
def prn: |
|||
if . == 1 then 0 |
|||
else . as $n |
|||
| (($n-1)|tostring|length) as $w |
|||
| [limit($w; inputs)] | join("") | tonumber |
|||
| if . < $n then . else ($n | prn) end |
|||
end; |
|||
def round($ndec): pow(10;$ndec) as $p | . * $p | round / $p; |
|||
# Output: {n, heads, wakings} |
|||
def sleepingBeauty: |
|||
{ n: ., wakings: 0, heads: 0 } |
|||
| reduce range(0; .n) as $i (.; |
|||
(2|prn) as $coin # heads = 0, tails = 1 say |
|||
| .wakings += 1 |
|||
| if $coin == 0 then .heads += 1 |
|||
else .wakings += 1 |
|||
end ); |
|||
1000000 |
|||
| sleepingBeauty |
|||
| "Wakings over \(.n) repetitions = \(.wakings).", |
|||
"Percentage probability of heads on waking = \(100*.heads/.wakings | round(3))%" |
|||
</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
Wakings over 1000000 repetitions = 1499524. |
|||
Percentage probability of heads on waking = 33.375% |
|||
</pre> |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |
||
< |
<syntaxhighlight lang="julia">""" |
||
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see |
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see |
||
how often we had heads on waking Sleeping Beauty. |
how often we had heads on waking Sleeping Beauty. |
||
Line 523: | Line 737: | ||
CREDENCE = sleeping_beauty_experiment(1_000_000) |
CREDENCE = sleeping_beauty_experiment(1_000_000) |
||
println("Results of experiment: Sleeping Beauty should estimate a credence of: ", CREDENCE) |
println("Results of experiment: Sleeping Beauty should estimate a credence of: ", CREDENCE) |
||
</ |
</syntaxhighlight>{{out}}<pre> |
||
Wakenings over 1000000 experiments: 1499534 |
Wakenings over 1000000 experiments: 1499534 |
||
Results of experiment: Sleeping Beauty should estimate a credence of: 0.33374768428058316 |
Results of experiment: Sleeping Beauty should estimate a credence of: 0.33374768428058316 |
||
Line 529: | Line 743: | ||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
||
< |
<syntaxhighlight lang="mathematica">ClearAll[SleepingBeautyExperiment] |
||
SleepingBeautyExperiment[reps_Integer] := Module[{gotheadsonwaking, wakenings, coinresult}, |
SleepingBeautyExperiment[reps_Integer] := Module[{gotheadsonwaking, wakenings, coinresult}, |
||
gotheadsonwaking = 0; |
gotheadsonwaking = 0; |
||
Line 548: | Line 762: | ||
] |
] |
||
out = N@SleepingBeautyExperiment[10^6]; |
out = N@SleepingBeautyExperiment[10^6]; |
||
Print["Results of experiment: Sleeping Beauty should estimate a credence of: ", out]</ |
Print["Results of experiment: Sleeping Beauty should estimate a credence of: ", out]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Wakenings over 1000000 experiments: 1499714 |
<pre>Wakenings over 1000000 experiments: 1499714 |
||
Line 554: | Line 768: | ||
=={{header|Nim}}== |
=={{header|Nim}}== |
||
< |
<syntaxhighlight lang="nim">import random |
||
const N = 1_000_000 |
const N = 1_000_000 |
||
Line 573: | Line 787: | ||
echo "Wakenings over ", N, " experiments: ", wakenings |
echo "Wakenings over ", N, " experiments: ", wakenings |
||
echo "Sleeping Beauty should estimate a credence of: ", onHeads / wakenings</ |
echo "Sleeping Beauty should estimate a credence of: ", onHeads / wakenings</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Wakenings over 1000000 experiments: 1499971 |
<pre>Wakenings over 1000000 experiments: 1499971 |
||
Sleeping Beauty should estimate a credence of: 0.3333591116094911</pre> |
Sleeping Beauty should estimate a credence of: 0.3333591116094911</pre> |
||
=={{header|Oberon-07}}== |
|||
{{Trans|Wren}} |
|||
{{works with|Oberonc (Oberon-07 compiler for the JVM)}} |
|||
For this task we need random numbers, we first define a DEFINITION module that will allow Oberon-07 code compiled with [[Oberonc_(Oberon-07_compiler_for_the_JVM)|oberonc]] to call methods in a [[Java]] class to obtain random integers: |
|||
<syntaxhighlight lang="modula2"> |
|||
(* Random numbers interface between Oberon-07 and java.util.Random *) |
|||
DEFINITION RandomNumbers; |
|||
(* Returns a random integer in the range 0 .. n - 1 *) |
|||
PROCEDURE randomInt( n : INTEGER ) : INTEGER; |
|||
END RandomNumbers. |
|||
</syntaxhighlight> |
|||
We also need to define the actual code of the RandomNumbers module in Java: |
|||
<syntaxhighlight lang="java"> |
|||
// java class for the Oberon-07 RandomNumbers module |
|||
import java.util.Random; |
|||
public class RandomNumbers |
|||
{ |
|||
private static java.util.Random rnd = new java.util.Random(); |
|||
private RandomNumbers(){} // this class can't be instantiated |
|||
public static int randomInt( int n ) |
|||
{ |
|||
return rnd.nextInt( n ); |
|||
} // randomInt |
|||
} // RandomNumbers |
|||
</syntaxhighlight> |
|||
After compiling the above Oberon-07 and Java sources, we can now use them in the SleepingBeauty module to solve the Task: |
|||
<syntaxhighlight lang="modula2"> |
|||
(* sleeping beauty problem - translated from the Wren sample *) |
|||
MODULE SleepingBeauty; |
|||
IMPORT |
|||
Out, RandomNumbers; |
|||
VAR pc : REAL; |
|||
PROCEDURE sleepingBeauty( reps : INTEGER ) : REAL; |
|||
VAR wakings, heads, i : INTEGER; |
|||
BEGIN |
|||
wakings := 0; heads := 0; |
|||
FOR i := 1 TO reps DO |
|||
wakings := wakings + 1; |
|||
IF RandomNumbers.randomInt( 2 ) = 1 THEN (* 1 = heads, 0 = tails say *) |
|||
heads := heads + 1 |
|||
ELSE |
|||
wakings := wakings + 1 |
|||
END |
|||
END; |
|||
Out.String( "Wakings over " );Out.Int( reps, 0 ); |
|||
Out.String( " repetitions = " );Out.Int( wakings, 0 );Out.Ln |
|||
RETURN ( FLT( heads ) / FLT( wakings ) ) * 100.0 |
|||
END sleepingBeauty; |
|||
BEGIN |
|||
pc := sleepingBeauty( 1000000 ); |
|||
Out.String( "Percentage probability of heads on waking = " );Out.Real( pc, 10 );Out.String( "%" );Out.Ln |
|||
END SleepingBeauty. |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Wakings over 1000000 repetitions = 1500298 |
|||
Percentage probability of heads on waking = 33.306850% |
|||
</pre> |
|||
=={{header|Pascal}}== |
=={{header|Pascal}}== |
||
{{trans|Phix}} |
{{trans|Phix}} |
||
< |
<syntaxhighlight lang="pascal"> |
||
program sleepBeau; |
program sleepBeau; |
||
uses |
uses |
||
Line 603: | Line 889: | ||
end; |
end; |
||
writeln(Format(fmt,[iterations,wakings,heads/wakings*100])); |
writeln(Format(fmt,[iterations,wakings,heads/wakings*100])); |
||
end.</ |
end.</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Wakings over 1000000 repetitions = 1499741 |
<pre>Wakings over 1000000 repetitions = 1499741 |
||
Line 609: | Line 895: | ||
=={{header|Perl}}== |
=={{header|Perl}}== |
||
< |
<syntaxhighlight lang="perl">use strict; |
||
use warnings; |
use warnings; |
||
Line 620: | Line 906: | ||
my $trials = 1_000_000; |
my $trials = 1_000_000; |
||
printf "Wakenings over $trials experiments: %d\nSleeping Beauty should estimate a credence of: %.4f\n", sleeping_beauty($trials);</ |
printf "Wakenings over $trials experiments: %d\nSleeping Beauty should estimate a credence of: %.4f\n", sleeping_beauty($trials);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Wakenings over 1000000 experiments: 1499816 |
<pre>Wakenings over 1000000 experiments: 1499816 |
||
Line 626: | Line 912: | ||
=={{header|Phix}}== |
=={{header|Phix}}== |
||
<!--< |
<!--<syntaxhighlight lang="phix">(phixonline)--> |
||
<span style="color: #008080;">constant</span> <span style="color: #000000;">iterations</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1_000_000</span><span style="color: #0000FF;">,</span> |
<span style="color: #008080;">constant</span> <span style="color: #000000;">iterations</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1_000_000</span><span style="color: #0000FF;">,</span> |
||
<span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""" |
<span style="color: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">""" |
||
Line 639: | Line 925: | ||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span> |
||
<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: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">iterations</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wakings</span><span style="color: #0000FF;">,</span><span style="color: #000000;">heads</span><span style="color: #0000FF;">/</span><span style="color: #000000;">wakings</span><span style="color: #0000FF;">*</span><span style="color: #000000;">100</span><span style="color: #0000FF;">})</span> |
<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: #000000;">fmt</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">iterations</span><span style="color: #0000FF;">,</span><span style="color: #000000;">wakings</span><span style="color: #0000FF;">,</span><span style="color: #000000;">heads</span><span style="color: #0000FF;">/</span><span style="color: #000000;">wakings</span><span style="color: #0000FF;">*</span><span style="color: #000000;">100</span><span style="color: #0000FF;">})</span> |
||
<!--</ |
<!--</syntaxhighlight>--> |
||
{{out}} |
{{out}} |
||
<small>(You'll get the exact result less than 1% of the time!!)</small> |
<small>(You'll get the exact result less than 1% of the time!!)</small> |
||
Line 649: | Line 935: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
===Procedural=== |
===Procedural=== |
||
< |
<syntaxhighlight lang="python">from random import choice |
||
def sleeping_beauty_experiment(repetitions): |
def sleeping_beauty_experiment(repetitions): |
||
Line 683: | Line 969: | ||
CREDENCE = sleeping_beauty_experiment(1_000_000) |
CREDENCE = sleeping_beauty_experiment(1_000_000) |
||
print("Results of experiment: Sleeping Beauty should estimate a credence of:", CREDENCE) |
print("Results of experiment: Sleeping Beauty should estimate a credence of:", CREDENCE) |
||
</ |
</syntaxhighlight>{{out}}<pre> |
||
Wakenings over 1000000 experiments: 1499765 |
Wakenings over 1000000 experiments: 1499765 |
||
Results of experiment: Sleeping Beauty should estimate a credence of: 0.333542254953276 |
Results of experiment: Sleeping Beauty should estimate a credence of: 0.333542254953276 |
||
Line 691: | Line 977: | ||
===Functional=== |
===Functional=== |
||
< |
<syntaxhighlight lang="python">'''Sleeping Beauty Problem''' |
||
from random import choice |
from random import choice |
||
Line 750: | Line 1,036: | ||
if __name__ == '__main__': |
if __name__ == '__main__': |
||
main() |
main() |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{Out}} |
{{Out}} |
||
<pre>1500188 wakenings over 1000000 experiments. |
<pre>1500188 wakenings over 1000000 experiments. |
||
Line 759: | Line 1,045: | ||
=={{header|Quackery}}== |
=={{header|Quackery}}== |
||
< |
<syntaxhighlight lang="quackery"> [ $ "bigrat.qky" loadfile ] now! |
||
[ say "Number of trials: " |
[ say "Number of trials: " |
||
Line 778: | Line 1,064: | ||
10 round vulgar$ echo$ cr ] is trials ( n --> n/d ) |
10 round vulgar$ echo$ cr ] is trials ( n --> n/d ) |
||
1000000 trials</ |
1000000 trials</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 791: | Line 1,077: | ||
=={{header|R}}== |
=={{header|R}}== |
||
There's nothing complicated here. Pretty much every language that resembles C is going to use virtually the same solution. |
There's nothing complicated here. Pretty much every language that resembles C is going to use virtually the same solution. |
||
< |
<syntaxhighlight lang="rsplus">beautyProblem <- function(n) |
||
{ |
{ |
||
wakeCount <- headCount <- 0 |
wakeCount <- headCount <- 0 |
||
Line 801: | Line 1,087: | ||
headCount/wakeCount |
headCount/wakeCount |
||
} |
} |
||
print(beautyProblem(10000000))</ |
print(beautyProblem(10000000))</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>[1] 0.3335838</pre> |
<pre>[1] 0.3335838</pre> |
||
Line 807: | Line 1,093: | ||
=={{header|Raku}}== |
=={{header|Raku}}== |
||
<lang |
<syntaxhighlight lang="raku" line>sub sleeping-beauty ($trials) { |
||
my $gotheadsonwaking = 0; |
my $gotheadsonwaking = 0; |
||
my $wakenings = 0; |
my $wakenings = 0; |
||
Line 821: | Line 1,107: | ||
} |
} |
||
say "Results of experiment: Sleeping Beauty should estimate a credence of: ", sleeping-beauty(1_000_000);</ |
say "Results of experiment: Sleeping Beauty should estimate a credence of: ", sleeping-beauty(1_000_000);</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre>Wakenings over 1000000 experiments: 1500040 |
<pre>Wakenings over 1000000 experiments: 1500040 |
||
Line 827: | Line 1,113: | ||
=={{header|Red}}== |
=={{header|Red}}== |
||
< |
<syntaxhighlight lang="rebol">Red ["Sleeping Beauty problem"] |
||
experiments: 1'000'000 |
experiments: 1'000'000 |
||
Line 836: | Line 1,122: | ||
] |
] |
||
print ["Awakenings over" experiments "experiments:" awakenings] |
print ["Awakenings over" experiments "experiments:" awakenings] |
||
print ["Probability of heads on waking:" heads / awakenings]</ |
print ["Probability of heads on waking:" heads / awakenings]</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
Line 845: | Line 1,131: | ||
=={{header|REXX}}== |
=={{header|REXX}}== |
||
When using Regina REXX, the seed specified (for '''random''') was '''46'''. |
When using Regina REXX, the seed specified (for '''random''') was '''46'''. |
||
< |
<syntaxhighlight lang="rexx">/*REXX pgm uses a Monte Carlo estimate for the results for the Sleeping Beauty problem. */ |
||
parse arg n seed . /*obtain optional arguments from the CL*/ |
parse arg n seed . /*obtain optional arguments from the CL*/ |
||
if n=='' | n=="," then n= 1000000 /*Not specified? Then use the default.*/ |
if n=='' | n=="," then n= 1000000 /*Not specified? Then use the default.*/ |
||
Line 859: | Line 1,145: | ||
exit 0 /*stick a fork in it, we're all done. */ |
exit 0 /*stick a fork in it, we're all done. */ |
||
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
/*──────────────────────────────────────────────────────────────────────────────────────*/ |
||
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?</ |
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?</syntaxhighlight> |
||
{{out|output|text= when using the input of: <tt> , 46 </tt>}} |
{{out|output|text= when using the input of: <tt> , 46 </tt>}} |
||
<pre> |
<pre> |
||
Line 868: | Line 1,154: | ||
=={{header|Ruby}}== |
=={{header|Ruby}}== |
||
{{trans|Python}} |
{{trans|Python}} |
||
< |
<syntaxhighlight lang="ruby">def sleeping_beauty_experiment(n) |
||
coin = [:heads, :tails] |
coin = [:heads, :tails] |
||
gotheadsonwaking = 0 |
gotheadsonwaking = 0 |
||
Line 882: | Line 1,168: | ||
puts "Results of experiment: Sleeping Beauty should estimate |
puts "Results of experiment: Sleeping Beauty should estimate |
||
a credence of: #{sleeping_beauty_experiment(1_000_000)}" |
a credence of: #{sleeping_beauty_experiment(1_000_000)}" |
||
</syntaxhighlight> |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>Wakenings over 1000000 experiments: 1499604 |
<pre>Wakenings over 1000000 experiments: 1499604 |
||
Line 889: | Line 1,175: | ||
</pre> |
</pre> |
||
=={{header|Swift}}== |
=={{header|Swift}}== |
||
< |
<syntaxhighlight lang="swift">let experiments = 1000000 |
||
var heads = 0 |
var heads = 0 |
||
var wakenings = 0 |
var wakenings = 0 |
||
Line 902: | Line 1,188: | ||
} |
} |
||
print("Wakenings over \(experiments) experiments: \(wakenings)") |
print("Wakenings over \(experiments) experiments: \(wakenings)") |
||
print("Sleeping Beauty should estimate a credence of: \(Double(heads) / Double(wakenings))")</ |
print("Sleeping Beauty should estimate a credence of: \(Double(heads) / Double(wakenings))")</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 910: | Line 1,196: | ||
</pre> |
</pre> |
||
=={{header|Vlang}}== |
=={{header|V (Vlang)}}== |
||
{{trans|Go}} |
{{trans|Go}} |
||
<lang vlang>import rand |
<syntaxhighlight lang="v (vlang)">import rand |
||
import rand.seed |
import rand.seed |
||
Line 935: | Line 1,221: | ||
pc := sleeping_beauty(1000000) |
pc := sleeping_beauty(1000000) |
||
println("Percentage probability of heads on waking = $pc%") |
println("Percentage probability of heads on waking = $pc%") |
||
}</ |
}</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 946: | Line 1,232: | ||
=={{header|Wren}}== |
=={{header|Wren}}== |
||
{{libheader|Wren-fmt}} |
{{libheader|Wren-fmt}} |
||
< |
<syntaxhighlight lang="wren">import "random" for Random |
||
import "/fmt" for Fmt |
import "./fmt" for Fmt |
||
var rand = Random.new() |
var rand = Random.new() |
||
Line 968: | Line 1,254: | ||
var pc = sleepingBeauty.call(1e6) |
var pc = sleepingBeauty.call(1e6) |
||
Fmt.print("Percentage probability of heads on waking = $f\%", pc)</ |
Fmt.print("Percentage probability of heads on waking = $f\%", pc)</syntaxhighlight> |
||
{{out}} |
{{out}} |
||
Line 975: | Line 1,261: | ||
Wakings over 1,000,000 repetitions = 1,500,321 |
Wakings over 1,000,000 repetitions = 1,500,321 |
||
Percentage probability of heads on waking = 33.304806% |
Percentage probability of heads on waking = 33.304806% |
||
</pre> |
|||
=={{header|XPL0}}== |
|||
{{trans|Wren}} |
|||
<syntaxhighlight lang "XPL0">include xpllib; \for Print |
|||
func real SleepingBeauty(Reps); |
|||
int Reps, Wakings, Heads, Coin, I; |
|||
[Wakings:= 0; Heads:= 0; |
|||
for I:= 0 to Reps-1 do |
|||
[Coin:= Ran(2); \heads = 0, tails = 1 say |
|||
Wakings:= Wakings + 1; |
|||
if Coin = 0 then Heads:= Heads + 1 |
|||
else Wakings:= Wakings + 1; |
|||
]; |
|||
Print("Wakings over %d repetitions = %d\n", Reps, Wakings); |
|||
return float(Heads) / float(Wakings) * 100.; |
|||
]; |
|||
real PC; |
|||
[PC:= SleepingBeauty(1_000_000); |
|||
Print("Percentage probability of heads on waking = %1.6f\%\n", PC); |
|||
]</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Wakings over 1000000 repetitions = 1500013 |
|||
Percentage probability of heads on waking = 33.332178% |
|||
</pre> |
</pre> |
Latest revision as of 07:23, 8 June 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss.
If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to
estimate the probability that the coin toss was heads. Her estimate is recorded and she is
then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied.
If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to
estimate the probability the coin toss was heads, but is then given a drug which makes her forget
that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day
later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss
was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday.
Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always estimate the probability of heads as 1/2, since she does not have any additional information. Others have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate should be 1/3 heads.
- Task
Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty is asked the question.
11l
F sleeping_beauty_experiment(repetitions)
‘
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see
how often we had heads on waking Sleeping Beauty.
’
V gotheadsonwaking = 0
V wakenings = 0
L 0 .< repetitions
V coin_result = random:choice([‘heads’, ‘tails’])
// On Monday, we check if we got heads.
wakenings++
I coin_result == ‘heads’
gotheadsonwaking++
// If tails, we do this again, but of course we will not add as if it was heads..
I coin_result == ‘tails’
wakenings++
I coin_result == ‘heads’
gotheadsonwaking++ // never done
print(‘Wakenings over ’repetitions‘ experiments: ’wakenings)
R Float(gotheadsonwaking) / wakenings
V CREDENCE = sleeping_beauty_experiment(1'000'000)
print(‘Results of experiment: Sleeping Beauty should estimate a credence of: ’CREDENCE)
- Output:
Wakenings over 1000000 experiments: 1500892 Results of experiment: Sleeping Beauty should estimate a credence of: 0.332540916
ALGOL 68
In Algol 68, the generated random numbers are in the semi-open range [0.0..1.0).
BEGIN # sleeping beauty problem - translated from the Wren sample #
PROC sleeping beauty = ( INT reps )REAL:
BEGIN
INT wakings := 0, heads := 0;
FOR i TO reps DO
wakings +:= 1;
IF next random < 0.5 THEN # [0..0.5) = heads, [0.5..1.0) = tails say #
heads +:= 1
ELSE
wakings +:= 1
FI
OD;
print( ( "Wakings over ", whole( reps, 0 ), " repetitions = ", whole( wakings, 0 ), newline ) );
( heads / wakings ) * 100
END; # sleeping beauty #
REAL pc = sleeping beauty( 1 000 000 );
print( ( "Percentage probability of heads on waking = ", fixed( pc, -10, 6 ), "%", newline ) )
END
- Output:
Wakings over 1000000 repetitions = 1499978 Percentage probability of heads on waking = 33.335289%
Arturo
sleepingBeauty: function [reps][
wakings: 0
heads: 0
do.times: reps [
coin: random 0 1
wakings: wakings + 1
if? coin = 0 -> heads: heads + 1
else -> wakings: wakings + 1
]
print ["Wakings over" reps "repetitions =" wakings]
return 100.0 * heads//wakings
]
pc: sleepingBeauty 100000
print ["Percentage probability of heads on waking =" pc "%"]
- Output:
Wakings over 100000 repetitions = 150096 Percentage probability of heads on waking = 33.24805457840316 %
BASIC
BASIC256
iteraciones = 1000000
cara = 0
dormir = 0
for i = 1 to iteraciones
lanza_moneda = int(rand * 2)
dormir = dormir + 1
if lanza_moneda = 1 then
cara = cara + 1
else
dormir = dormir + 1
end if
next i
print "Wakings over "; iteraciones; " repetitions = "; dormir
print "Percentage probability of heads on waking = "; (cara/dormir*100); "%"
end
- Output:
Igual que la entrada de FreeBASIC.
FreeBASIC
Const iteraciones = 1000000
Randomize Timer
Dim As Uinteger cara = 0, dormir = 0
For i As Uinteger = 1 To iteraciones
Dim As integer lanza_moneda = Int(Rnd * 2) + 1
dormir += 1
if lanza_moneda = 1 then cara += 1 else dormir += 1
Next i
Print Using "Wakings over #####,### repetitions = #####,###"; iteraciones ; dormir
Print using "Percentage probability of heads on waking = ###.######%"; (cara/dormir*100)'; "%"
Sleep
- Output:
Wakings over 1,000,000 repetitions = 1,499,718 Percentage probability of heads on waking = 33.358405%
GW-BASIC
In this simulation, Sleeping Beauty flips a coin of her own.
10 RANDOMIZE TIMER
20 MONDAY = 0 : TUESDAY = 1
30 HEADS = 0 : TAILS = 1
40 FOR SB = 1 TO 300000!
50 IF COIN = HEADS THEN GOSUB 150 ELSE GOSUB 210
60 COIN = INT(RND*2)
70 NEXT SB
80 PRINT "Sleeping Beauty was put through this experiment ";SB-1;" times."
90 PRINT "She was awoken ";AWAKE;" times."
100 PRINT "She guessed heads ";CHEADS+WHEADS;" times."
110 PRINT "Those guesses were correct ";CHEADS;" times. ";100*CHEADS/(CHEADS+WHEADS);"%"
120 PRINT "She guessed tails ";WTAILS+CTAILS;" times."
130 PRINT "Those guesses were correct ";CTAILS;" times. ";100*CTAILS/(CTAILS+WTAILS);"%"
140 END
150 REM interview if the coin came up heads
160 AWAKE = AWAKE + 1
170 NHEADS = NHEADS + 1
180 GUESS = INT(RND*2)
190 IF GUESS = HEADS THEN CHEADS = CHEADS + 1 ELSE WTAILS = WTAILS + 1
200 RETURN
210 REM interviews if the coin came up tails
220 FOR DAY = MONDAY TO TUESDAY
230 AWAKE = AWAKE + 1
240 GUESS = INT(RND*2)
250 IF GUESS = HEADS THEN WHEADS = WHEADS + 1 ELSE CTAILS = CTAILS + 1
260 NEXT DAY
270 RETURN
- Output:
Sleeping Beauty was put through this experiment 300000 times. She was awoken 449981 times. She guessed heads 224569 times. Those guesses were correct 74985 times. 33.39063 % She guessed tails 225412 times. Those guesses were correct 150378 times. 66.71251 %
Yabasic
iteraciones = 1000000
cara = 0
dormir = 0
for i = 1 to iteraciones
lanza_moneda = int(ran(2))
dormir = dormir + 1
if lanza_moneda = 1 then cara = cara + 1 else dormir = dormir + 1 endif
next i
print "Wakings over ", iteraciones, " repetitions = ", dormir
print "Percentage probability of heads on waking = ", (cara/dormir*100), "%"
end
- Output:
Igual que la entrada de FreeBASIC.
C++
#include <iostream>
#include <random>
int main() {
std::cout.imbue(std::locale(""));
const int experiments = 1000000;
std::random_device dev;
std::default_random_engine engine(dev());
std::uniform_int_distribution<int> distribution(0, 1);
int heads = 0, wakenings = 0;
for (int i = 0; i < experiments; ++i) {
++wakenings;
switch (distribution(engine)) {
case 0: // heads
++heads;
break;
case 1: // tails
++wakenings;
break;
}
}
std::cout << "Wakenings over " << experiments
<< " experiments: " << wakenings << '\n';
std::cout << "Sleeping Beauty should estimate a credence of: "
<< double(heads) / wakenings << '\n';
}
- Output:
Wakenings over 1,000,000 experiments: 1,500,090 Sleeping Beauty should estimate a credence of: 0.333253
CLU
% This program needs to be merged with PCLU's "misc" library
% to use the random number generator.
experiment = cluster is run
rep = null
own awake: int := 0
own awake_heads: int := 0
% Returns true if heads, false if tails
coin_toss = proc () returns (bool)
return(random$next(2)=1)
end coin_toss
% Do the experiment once
do_experiment = proc ()
heads: bool := coin_toss()
% monday - wake up
awake := awake + 1
if heads then
awake_heads := awake_heads + 1
return
end
% tuesday - wake up if tails
awake := awake + 1
end do_experiment
% Run the experiment N times
run = proc (n: int) returns (real)
awake := 0
awake_heads := 0
for i: int in int$from_to(1,n) do
do_experiment()
end
return(real$i2r(awake_heads) / real$i2r(awake))
end run
end experiment
start_up = proc ()
N = 1000000
po: stream := stream$primary_output()
stream$puts(po, "Chance of waking up with heads: ")
chance: real := experiment$run(N)
stream$putl(po, f_form(chance, 1, 6))
end start_up
- Output:
Chance of waking up with heads: 0.333758
Dyalect
let experiments = 10000
var heads = 0
var wakenings = 0
for _ in 1..experiments {
wakenings += 1
match rnd(min: 0, max: 10) {
<5 => heads += 1,
_ => wakenings += 1
}
}
print("Wakenings over \(experiments) experiments: \(wakenings)")
print("Sleeping Beauty should estimate a credence of: \(Float(heads) / Float(wakenings))")
EasyLang
reps = 1e6
for i to reps
coin = randint 2
wakings += 1
if coin = 1
heads += 1
else
wakings += 1
.
.
print "Chance of waking up with heads: " & heads / wakings * 100 & "%"
Excel
LAMBDA
Binding the name SLEEPINGB to the lambda expression below in the Excel Workbook Name Manager:
(See LAMBDA: The ultimate Excel worksheet function)
SLEEPINGB
=LAMBDA(n,
LET(
headsWakes, LAMBDA(x,
IF(1 = x,
{1,1},
{0,2}
)
)(
RANDARRAY(n, 1, 0, 1, TRUE)
),
CHOOSE(
{1,2},
SUM(INDEX(headsWakes, 0, 1)),
SUM(INDEX(headsWakes, 0, 2))
)
)
)
- Output:
The pair of values in cells B2 and C2 both result from the application of SLEEPINGB in B2.
The credence value is returned as a ratio by the expression B2/C2 in cell D2,
with the format setting Number > Fraction > Up to three digits.
fx | =SLEEPINGB(1000000) | ||||
---|---|---|---|---|---|
A | B | C | D | ||
1 | Heads | Wakenings | Credence | ||
2 | Results | 500111 | 1499889 | 1/3 |
F#
// Sleeping Beauty: Nigel Galloway. May 16th., 2021
let heads,woken=let n=System.Random() in {1..1000}|>Seq.fold(fun(h,w) g->match n.Next(2) with 0->(h+1,w+1) |_->(h,w+2))(0,0)
printfn "During 1000 tosses Sleeping Beauty woke %d times, %d times the toss was heads. %.0f%% of times heads had been tossed when she awoke" woken heads (100.0*float(heads)/float(woken))
- Output:
During 1000 tosses Sleeping Beauty woke 1519 times, 481 times the toss was heads. 32% of times heads had been tossed when she awoke
Factor
USING: combinators.random io kernel math prettyprint ;
: sleeping ( n -- heads wakenings )
0 0 rot [ 1 + .5 [ [ 1 + ] dip ] [ 1 + ] ifp ] times ;
"Wakenings over 1,000,000 experiments: " write
1e6 sleeping dup . /f
"Sleeping Beauty should estimate a credence of: " write .
- Output:
Wakenings over 1,000,000 experiments: 1500127 Sleeping Beauty should estimate a credence of: 0.3332204540015612
Fortran
Uses random_number from the Fortran 95 standard.
program sleepingbeauty
implicit none
integer :: total_reps
integer :: result_wakings
real :: result_percent
total_reps = 1e6
call sleepingOp(total_reps, result_wakings, result_percent)
print *, "wakings over", total_reps, "reps: ", result_wakings
print *, "percentage probability of heads on wake:", result_percent
contains
subroutine sleepingOp(reps, wakings, percent)
integer, intent(in) :: reps
integer, intent(out) :: wakings
real, intent(out) :: percent
integer :: heads
integer :: i
real :: coin
wakings = 0
heads = 0
do i = 0, reps, 1
call random_number(coin)
wakings = wakings + 1
if (coin > 0.5) then
heads = heads + 1
else
wakings = wakings + 1
end if
end do
percent = real(heads) / real(wakings)
end subroutine sleepingOp
end program sleepingbeauty
- Output:
wakings over 1000000 reps: 1500326 percentage probability of heads on wake: 0.333044946
FutureBasic
_iterations = 1000000
local fn SleepingBeauty
NSUInteger i
CGFloat heads = 0, sleep = 0
for i = 1 to _iterations
NSInteger coinToss = int( rnd(2) )
sleep++
if coinToss = 1 then heads++ else sleep++
next
printf @"Awakenings over %lld sleep cycles = %.f", _iterations, sleep
printf @"Percent probability of heads on waking = %.4f%%", heads / sleep * 100
end fn
randomize
fn SleepingBeauty
HandleEvents
- Output:
Awakenings over 1000000 sleep cycles = 1499725 Percent probability of heads on waking = 33.3578%
Go
package main
import (
"fmt"
"math/rand"
"rcu"
"time"
)
func sleepingBeauty(reps int) float64 {
wakings := 0
heads := 0
for i := 0; i < reps; i++ {
coin := rand.Intn(2) // heads = 0, tails = 1 say
wakings++
if coin == 0 {
heads++
} else {
wakings++
}
}
fmt.Printf("Wakings over %s repetitions = %s\n", rcu.Commatize(reps), rcu.Commatize(wakings))
return float64(heads) / float64(wakings) * 100
}
func main() {
rand.Seed(time.Now().UnixNano())
pc := sleepingBeauty(1e6)
fmt.Printf("Percentage probability of heads on waking = %f%%\n", pc)
}
- Output:
Sample run:
Wakings over 1,000,000 repetitions = 1,500,256 Percentage probability of heads on waking = 33.310582%
Haskell
import Data.Monoid (Sum(..))
import System.Random (randomIO)
import Control.Monad (replicateM)
import Data.Bool (bool)
data Toss = Heads | Tails deriving Show
anExperiment toss =
moreWakenings <>
case toss of
Heads -> headsOnWaking
Tails -> moreWakenings
where
moreWakenings = (1,0)
headsOnWaking = (0,1)
main = do
tosses <- map (bool Heads Tails) <$> replicateM 1000000 randomIO
let (Sum w, Sum h) = foldMap anExperiment tosses
let ratio = fromIntegral h / fromIntegral w
putStrLn $ "Ratio: " ++ show ratio
*Main> main Ratio: 0.33339378051805013
J
Simulation code:
sb=: {{
monday=. ?2
if. -. monday do.
tuesday=. ?2
<monday,tuesday
else.
<monday
end.
}}
Results:
sample=: sb"0 i.1e6 NB. simulate a million mondays
#sample NB. number of experiments
1000000
#;sample NB. number of questions
1500433
+/;sample NB. number of heads
749617
+/0={.@>sample NB. how many times was sleeping beauty drugged?
500433
(+/%#);sample NB. odds of heads at time of question
0.4996
sample+&#;sample NB. total number of awakenings
2500433
It's probably worth noting here that the number of heads divided by the number of awakenings would be about 0.3 -- but Sleeping Beauty was not asked to guess whether the coin was heads on Wednesday.
Java
import java.util.concurrent.ThreadLocalRandom;
public final class SleepingBeauty {
public static void main(String[] aArgs) {
final int experiments = 1_000_000;
ThreadLocalRandom random = ThreadLocalRandom.current();
enum Coin { HEADS, TAILS }
int heads = 0;
int awakenings = 0;
for ( int i = 0; i < experiments; i++ ) {
Coin coin = Coin.values()[random.nextInt(0, 2)];
switch ( coin ) {
case HEADS -> { awakenings += 1; heads += 1; }
case TAILS -> awakenings += 2;
}
}
System.out.println("Awakenings over " + experiments + " experiments: " + awakenings);
String credence = String.format("%.3f", (double) heads / awakenings);
System.out.println("Sleeping Beauty should estimate a credence of: " + credence);
}
}
- Output:
Awakenings over 1000000 experiments: 1499522 Sleeping Beauty should estimate a credence of: 0.334
jq
Adapted from Wren
Works with jq, the C implementation of jq
Works with gojq, the Go implementation of jq
Works with jaq, the Rust implementation of jq
Since jq does not currently have a built-in PRNG, /dev/random will be used as a source of entropy. An invocation of jq along the lines of the following would be appropriate in a typical command-line environment:
< /dev/random tr -cd '0-9' | fold -w 1 | jq -cnr -f sleeping.jq
where "sleeping.jq" is the name of a file containing the following jq program.
# Output: a PRN in range(0; .)
def prn:
if . == 1 then 0
else . as $n
| (($n-1)|tostring|length) as $w
| [limit($w; inputs)] | join("") | tonumber
| if . < $n then . else ($n | prn) end
end;
def round($ndec): pow(10;$ndec) as $p | . * $p | round / $p;
# Output: {n, heads, wakings}
def sleepingBeauty:
{ n: ., wakings: 0, heads: 0 }
| reduce range(0; .n) as $i (.;
(2|prn) as $coin # heads = 0, tails = 1 say
| .wakings += 1
| if $coin == 0 then .heads += 1
else .wakings += 1
end );
1000000
| sleepingBeauty
| "Wakings over \(.n) repetitions = \(.wakings).",
"Percentage probability of heads on waking = \(100*.heads/.wakings | round(3))%"
- Output:
Wakings over 1000000 repetitions = 1499524. Percentage probability of heads on waking = 33.375%
Julia
"""
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see
how often we had heads on waking Sleeping Beauty.
"""
function sleeping_beauty_experiment(repetitions)
gotheadsonwaking = 0
wakenings = 0
for _ in 1:repetitions
coin_result = rand(["heads", "tails"])
# On Monday, we check if we got heads.
wakenings += 1
if coin_result == "heads"
gotheadsonwaking += 1
end
# If tails, we do this again, but of course we will not add as if it was heads.
if coin_result == "tails"
wakenings += 1
if coin_result == "heads"
gotheadsonwaking += 1 # never done
end
end
end
# Show the number of times she was wakened.
println("Wakenings over ", repetitions, " experiments: ", wakenings)
# Return the number of correct bets SB made out of the total number
# of times she is awoken over all the experiments with that bet.
return gotheadsonwaking / wakenings
end
CREDENCE = sleeping_beauty_experiment(1_000_000)
println("Results of experiment: Sleeping Beauty should estimate a credence of: ", CREDENCE)
- Output:
Wakenings over 1000000 experiments: 1499534 Results of experiment: Sleeping Beauty should estimate a credence of: 0.33374768428058316
Mathematica/Wolfram Language
ClearAll[SleepingBeautyExperiment]
SleepingBeautyExperiment[reps_Integer] := Module[{gotheadsonwaking, wakenings, coinresult},
gotheadsonwaking = 0;
wakenings = 0;
Do[
coinresult = RandomChoice[{"heads", "tails"}];
wakenings++;
If[coinresult === "heads",
gotheadsonwaking++;
,
wakenings++;
]
,
{reps}
];
Print["Wakenings over ", reps, " experiments: ", wakenings];
gotheadsonwaking/wakenings
]
out = N@SleepingBeautyExperiment[10^6];
Print["Results of experiment: Sleeping Beauty should estimate a credence of: ", out]
- Output:
Wakenings over 1000000 experiments: 1499714 Results of experiment: Sleeping Beauty should estimate a credence of: 0.333588
Nim
import random
const N = 1_000_000
type Side {.pure.} = enum Heads, Tails
const Sides = [Heads, Tails]
randomize()
var onHeads, wakenings = 0
for _ in 1..N:
let side = sample(Sides)
inc wakenings
if side == Heads:
inc onHeads
else:
inc wakenings
echo "Wakenings over ", N, " experiments: ", wakenings
echo "Sleeping Beauty should estimate a credence of: ", onHeads / wakenings
- Output:
Wakenings over 1000000 experiments: 1499971 Sleeping Beauty should estimate a credence of: 0.3333591116094911
Oberon-07
For this task we need random numbers, we first define a DEFINITION module that will allow Oberon-07 code compiled with oberonc to call methods in a Java class to obtain random integers:
(* Random numbers interface between Oberon-07 and java.util.Random *)
DEFINITION RandomNumbers;
(* Returns a random integer in the range 0 .. n - 1 *)
PROCEDURE randomInt( n : INTEGER ) : INTEGER;
END RandomNumbers.
We also need to define the actual code of the RandomNumbers module in Java:
// java class for the Oberon-07 RandomNumbers module
import java.util.Random;
public class RandomNumbers
{
private static java.util.Random rnd = new java.util.Random();
private RandomNumbers(){} // this class can't be instantiated
public static int randomInt( int n )
{
return rnd.nextInt( n );
} // randomInt
} // RandomNumbers
After compiling the above Oberon-07 and Java sources, we can now use them in the SleepingBeauty module to solve the Task:
(* sleeping beauty problem - translated from the Wren sample *)
MODULE SleepingBeauty;
IMPORT
Out, RandomNumbers;
VAR pc : REAL;
PROCEDURE sleepingBeauty( reps : INTEGER ) : REAL;
VAR wakings, heads, i : INTEGER;
BEGIN
wakings := 0; heads := 0;
FOR i := 1 TO reps DO
wakings := wakings + 1;
IF RandomNumbers.randomInt( 2 ) = 1 THEN (* 1 = heads, 0 = tails say *)
heads := heads + 1
ELSE
wakings := wakings + 1
END
END;
Out.String( "Wakings over " );Out.Int( reps, 0 );
Out.String( " repetitions = " );Out.Int( wakings, 0 );Out.Ln
RETURN ( FLT( heads ) / FLT( wakings ) ) * 100.0
END sleepingBeauty;
BEGIN
pc := sleepingBeauty( 1000000 );
Out.String( "Percentage probability of heads on waking = " );Out.Real( pc, 10 );Out.String( "%" );Out.Ln
END SleepingBeauty.
- Output:
Wakings over 1000000 repetitions = 1500298 Percentage probability of heads on waking = 33.306850%
Pascal
program sleepBeau;
uses
sysutils; //Format
const
iterations = 1000*1000;
fmt = 'Wakings over %d repetitions = %d'+#13#10+
'Percentage probability of heads on waking = %8.5f%%';
var
i,
heads,
wakings,
flip: Uint32;
begin
randomize;
for i :=1 to iterations do
Begin
flip := random(2)+1;//-- 1==heads, 2==tails
inc(wakings,1 + Ord(flip=2));
inc(heads,Ord(flip=1));
end;
writeln(Format(fmt,[iterations,wakings,heads/wakings*100]));
end.
- Output:
Wakings over 1000000 repetitions = 1499741 Percentage probability of heads on waking = 33.35636%
Perl
use strict;
use warnings;
sub sleeping_beauty {
my($trials) = @_;
my($gotheadsonwaking,$wakenings);
$wakenings++ and rand > .5 ? $gotheadsonwaking++ : $wakenings++ for 1..$trials;
$wakenings, $gotheadsonwaking/$wakenings
}
my $trials = 1_000_000;
printf "Wakenings over $trials experiments: %d\nSleeping Beauty should estimate a credence of: %.4f\n", sleeping_beauty($trials);
- Output:
Wakenings over 1000000 experiments: 1499816 Sleeping Beauty should estimate a credence of: 0.333
Phix
constant iterations = 1_000_000, fmt = """ Wakings over %,d repetitions = %,d Percentage probability of heads on waking = %f%% """ integer heads = 0, wakings = 0 for i=1 to iterations do integer flip = rand(2) -- 1==heads, 2==tails wakings += 1 + (flip==2) heads += (flip==1) end for printf(1,fmt,{iterations,wakings,heads/wakings*100})
- Output:
(You'll get the exact result less than 1% of the time!!)
Wakings over 1,000,000 repetitions = 1,500,000 Percentage probability of heads on waking = 33.333333%
Python
Procedural
from random import choice
def sleeping_beauty_experiment(repetitions):
"""
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see
how often we had heads on waking Sleeping Beauty.
"""
gotheadsonwaking = 0
wakenings = 0
for _ in range(repetitions):
coin_result = choice(["heads", "tails"])
# On Monday, we check if we got heads.
wakenings += 1
if coin_result == "heads":
gotheadsonwaking += 1
# If tails, we do this again, but of course we will not add as if it was heads..
if coin_result == "tails":
wakenings += 1
if coin_result == "heads":
gotheadsonwaking += 1 # never done
# Show the number of times she was wakened.
print("Wakenings over", repetitions, "experiments:", wakenings)
# Return the number of correct bets SB made out of the total number
# of times she is awoken over all the experiments with that bet.
return gotheadsonwaking / wakenings
CREDENCE = sleeping_beauty_experiment(1_000_000)
print("Results of experiment: Sleeping Beauty should estimate a credence of:", CREDENCE)
- Output:
Wakenings over 1000000 experiments: 1499765 Results of experiment: Sleeping Beauty should estimate a credence of: 0.333542254953276
Functional
'''Sleeping Beauty Problem'''
from random import choice
from itertools import repeat
from functools import reduce
# experiment :: (Int, Int) -> IO (Int, Int)
def experiment(headsWakings):
'''A pair of counts updated by a coin flip.
'''
heads, wakings = headsWakings
return (
1 + heads, 1 + wakings
) if "h" == choice(["h", "t"]) else (
heads, 2 + wakings
)
# ------------------------- TEST -------------------------
# main :: IO ()
def main():
'''Observed results from one million runs.'''
n = 1_000_000
heads, wakes = applyN(n)(
experiment
)(
(0, 0)
)
print(
f'{wakes} wakenings over {n} experiments.\n'
)
print('Sleeping Beauty should estimate credence')
print(f'at around {round(heads/wakes, 3)}')
# ----------------------- GENERIC ------------------------
# applyN :: Int -> (a -> a) -> a -> a
def applyN(n):
'''n applications of f.
(Church numeral n).
'''
def go(f):
def ga(a, g):
return g(a)
def fn(x):
return reduce(ga, repeat(f, n), x)
return fn
return go
# MAIN ---
if __name__ == '__main__':
main()
- Output:
1500188 wakenings over 1000000 experiments. Sleeping Beauty should estimate credence at around 0.333
Quackery
[ $ "bigrat.qky" loadfile ] now!
[ say "Number of trials: "
dup echo cr
0 ( heads count )
0 ( sleeps count )
rot times
[ 1+
2 random if
[ 1+ dip 1+ ] ]
say "Data: heads count: "
over echo cr
say " sleeps count: "
dup echo cr
say "Credence of heads: "
2dup 20 point$ echo$ cr
say " or approximately: "
10 round vulgar$ echo$ cr ] is trials ( n --> n/d )
1000000 trials
- Output:
Number of trials: 1000000 Data: heads count: 500212 sleeps count: 1500212 Credence of heads: 0.33342754224069664821 or approximately: 1/3
R
There's nothing complicated here. Pretty much every language that resembles C is going to use virtually the same solution.
beautyProblem <- function(n)
{
wakeCount <- headCount <- 0
for(i in seq_len(n))
{
wakeCount <- wakeCount + 1
if(sample(c("H", "T"), 1) == "H") headCount <- headCount + 1 else wakeCount <- wakeCount + 1
}
headCount/wakeCount
}
print(beautyProblem(10000000))
- Output:
[1] 0.3335838
Raku
sub sleeping-beauty ($trials) {
my $gotheadsonwaking = 0;
my $wakenings = 0;
^$trials .map: {
given <Heads Tails>.roll {
++$wakenings;
when 'Heads' { ++$gotheadsonwaking }
when 'Tails' { ++$wakenings }
}
}
say "Wakenings over $trials experiments: ", $wakenings;
$gotheadsonwaking / $wakenings
}
say "Results of experiment: Sleeping Beauty should estimate a credence of: ", sleeping-beauty(1_000_000);
- Output:
Wakenings over 1000000 experiments: 1500040 Results of experiment: Sleeping Beauty should estimate a credence of: 0.333298
Red
Red ["Sleeping Beauty problem"]
experiments: 1'000'000
heads: awakenings: 0
loop experiments [
awakenings: awakenings + 1
either 1 = random 2 [heads: heads + 1] [awakenings: awakenings + 1]
]
print ["Awakenings over" experiments "experiments:" awakenings]
print ["Probability of heads on waking:" heads / awakenings]
- Output:
Awakenings over 1000000 experiments: 1500063 Probability of heads on waking: 0.3332773356852345
REXX
When using Regina REXX, the seed specified (for random) was 46.
/*REXX pgm uses a Monte Carlo estimate for the results for the Sleeping Beauty problem. */
parse arg n seed . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 1000000 /*Not specified? Then use the default.*/
if datatype(seed, 'W') then call random ,,seed /* Specified? Then use as RAND seed*/
awake= 0 /* " " " " awakened. */
do #=0 for n /*perform experiment: 1 million times?*/
if random(,1) then awake= awake + 1 /*Sleeping Beauty is awoken. */
else #= # + 1 /* " " keeps sleeping. */
end /*#*/ /* [↑] RANDOM returns: 0 or 1 */
say 'Wakenings over ' commas(n) " repetitions: " commas(#)
say 'The percentage probability of heads on awakening: ' (awake / # * 100)"%"
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ?
- output when using the input of: , 46
Wakenings over 1,000,000 repetitions: 1,500,000 The percentage probability of heads on awakening: 33.3333333%
Ruby
def sleeping_beauty_experiment(n)
coin = [:heads, :tails]
gotheadsonwaking = 0
wakenings = 0
n.times do
wakenings += 1
coin.sample == :heads ? gotheadsonwaking += 1 : wakenings += 1
end
puts "Wakenings over #{n} experiments: #{wakenings}"
gotheadsonwaking / wakenings.to_f
end
puts "Results of experiment: Sleeping Beauty should estimate
a credence of: #{sleeping_beauty_experiment(1_000_000)}"
- Output:
Wakenings over 1000000 experiments: 1499604 Results of experiment: Sleeping Beauty should estimate a credence of: 0.3336854262858728
Swift
let experiments = 1000000
var heads = 0
var wakenings = 0
for _ in (1...experiments) {
wakenings += 1
switch (Int.random(in: 0...1)) {
case 0:
heads += 1
default:
wakenings += 1
}
}
print("Wakenings over \(experiments) experiments: \(wakenings)")
print("Sleeping Beauty should estimate a credence of: \(Double(heads) / Double(wakenings))")
- Output:
Wakenings over 1000000 experiments: 1500036 Sleeping Beauty should estimate a credence of: 0.3333013341013149
V (Vlang)
import rand
import rand.seed
fn sleeping_beauty(reps int) f64 {
mut wakings := 0
mut heads := 0
for _ in 0..reps {
coin := rand.intn(2) or {0} // heads = 0, tails = 1 say
wakings++
if coin == 0 {
heads++
} else {
wakings++
}
}
println("Wakings over $reps repetitions = $wakings")
return f64(heads) / f64(wakings) * 100
}
fn main() {
rand.seed(seed.time_seed_array(2))
pc := sleeping_beauty(1000000)
println("Percentage probability of heads on waking = $pc%")
}
- Output:
Sample run:
Wakings over 1000000 repetitions = 1500224 Percentage probability of heads on waking = 33.31342519517085%
Wren
import "random" for Random
import "./fmt" for Fmt
var rand = Random.new()
var sleepingBeauty = Fn.new { |reps|
var wakings = 0
var heads = 0
for (i in 0...reps) {
var coin = rand.int(2) // heads = 0, tails = 1 say
wakings = wakings + 1
if (coin == 0) {
heads = heads + 1
} else {
wakings = wakings + 1
}
}
Fmt.print("Wakings over $,d repetitions = $,d", reps, wakings)
return heads/wakings * 100
}
var pc = sleepingBeauty.call(1e6)
Fmt.print("Percentage probability of heads on waking = $f\%", pc)
- Output:
Sample run:
Wakings over 1,000,000 repetitions = 1,500,321 Percentage probability of heads on waking = 33.304806%
XPL0
include xpllib; \for Print
func real SleepingBeauty(Reps);
int Reps, Wakings, Heads, Coin, I;
[Wakings:= 0; Heads:= 0;
for I:= 0 to Reps-1 do
[Coin:= Ran(2); \heads = 0, tails = 1 say
Wakings:= Wakings + 1;
if Coin = 0 then Heads:= Heads + 1
else Wakings:= Wakings + 1;
];
Print("Wakings over %d repetitions = %d\n", Reps, Wakings);
return float(Heads) / float(Wakings) * 100.;
];
real PC;
[PC:= SleepingBeauty(1_000_000);
Print("Percentage probability of heads on waking = %1.6f\%\n", PC);
]
- Output:
Wakings over 1000000 repetitions = 1500013 Percentage probability of heads on waking = 33.332178%