Sleeping Beauty problem: Difference between revisions

Added Easylang
(→‎{{header|Excel}}: Added a draft for Excel LAMBDA)
(Added Easylang)
(45 intermediate revisions by 28 users not shown)
Line 1:
{{draft task|Decision Theory}}
 
;Background on the task
Line 6:
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.
Line 18:
<br />
 
Some decision makers have argued that since the coin toss was fair Sleeping BeatyBeauty 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
Line 27:
 
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.
 
 
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="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)</syntaxhighlight>
 
{{out}}
<pre>
Wakenings over 1000000 experiments: 1500892
Results of experiment: Sleeping Beauty should estimate a credence of: 0.332540916
</pre>
 
=={{header|Arturo}}==
 
{{trans|Wren}}
 
<syntaxhighlight lang="rebol">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 "%"]</syntaxhighlight>
 
{{out}}
 
<pre>Wakings over 100000 repetitions = 150096
Percentage probability of heads on waking = 33.24805457840316 %</pre>
 
=={{header|BASIC}}==
==={{header|BASIC256}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="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
</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
 
==={{header|FreeBASIC}}===
<syntaxhighlight lang="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
</syntaxhighlight>
{{out}}
<pre>
Wakings over 1,000,000 repetitions = 1,499,718
Percentage probability of heads on waking = 33.358405%
</pre>
 
==={{header|GW-BASIC}}===
In this simulation, Sleeping Beauty flips a coin of her own.
<syntaxhighlight lang="gwbasic">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</syntaxhighlight>
{{out}}<pre>
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 %
</pre>
 
==={{header|Yabasic}}===
{{trans|FreeBASIC}}
<syntaxhighlight lang="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
</syntaxhighlight>
{{out}}
<pre>
Igual que la entrada de FreeBASIC.
</pre>
 
=={{header|C++}}==
<langsyntaxhighlight lang="cpp">#include <iostream>
#include <random>
 
Line 58 ⟶ 229:
std::cout << "Sleeping Beauty should estimate a credence of: "
<< double(heads) / wakenings << '\n';
}</langsyntaxhighlight>
 
{{out}}
Line 65 ⟶ 236:
Sleeping Beauty should estimate a credence of: 0.333253
</pre>
 
=={{header|CLU}}==
<syntaxhighlight lang="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 </syntaxhighlight>
{{out}}
<pre>Chance of waking up with heads: 0.333758</pre>
 
=={{header|Dyalect}}==
{{trans|Swift}}
 
<syntaxhighlight lang="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))")</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}}==
Line 74 ⟶ 331:
 
{{Works with | Office 365 betas 2021}}
<langsyntaxhighlight lang="lisp">SLEEPINGB
=LAMBDA(n,
LET(
Line 85 ⟶ 342:
RANDARRAY(n, 1, 0, 1, TRUE)
),
TUPLECHOOSE(
SUM(INDEX(headsWakes{1, 02}, 1))
) SUM(INDEX(headsWakes, 0, 1)),
SUM(INDEX(headsWakes, 0, 2))
)
)
)</langsyntaxhighlight>
 
and also assuming that the name TUPLE is bound to the following generic lambda in the workbook's Name Manager:
 
<lang lisp>TUPLE
=LAMBDA(a,
LAMBDA(b,
CHOOSE({1,2}, a, b)
)
)</lang>
 
{{Out}}
 
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''.
 
{| class="wikitable"
Line 129 ⟶ 378:
| style="background-color:#cbcefb;" | 500111
| 1499889
| 1/3
| 0.33343200730187367
|}
 
=={{header|F_Sharp|F#}}==
 
<syntaxhighlight lang="fsharp">
 
// 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))
</syntaxhighlight>
{{out}}
<pre>
During 1000 tosses Sleeping Beauty woke 1519 times, 481 times the toss was heads. 32% of times heads had been tossed when she awoke
</pre>
=={{header|Factor}}==
{{works with|Factor|0.99 2021-02-05}}
<langsyntaxhighlight lang="factor">USING: combinators.random io kernel math prettyprint ;
 
: sleeping ( n -- heads wakenings )
Line 143 ⟶ 400:
"Wakenings over 1,000,000 experiments: " write
1e6 sleeping dup . /f
"Sleeping Beauty should estimate a credence of: " write .</langsyntaxhighlight>
{{out}}
<pre>
Wakenings over 1,000,000 experiments: 1500127
Sleeping Beauty should estimate a credence of: 0.3332204540015612
</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>
 
 
=={{header|Go}}==
{{trans|Wren}}
{{libheader|Go-rcu}}
<syntaxhighlight lang="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)
}</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
Wakings over 1,000,000 repetitions = 1,500,256
Percentage probability of heads on waking = 33.310582%
</pre>
 
=={{header|Haskell}}==
<syntaxhighlight lang="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</syntaxhighlight>
 
<pre>*Main> main
Ratio: 0.33339378051805013</pre>
 
=={{header|J}}==
Simulation code:
<syntaxhighlight lang="j">sb=: {{
monday=. ?2
if. -. monday do.
tuesday=. ?2
<monday,tuesday
else.
<monday
end.
}}</syntaxhighlight>
 
Results:<syntaxhighlight lang="j"> 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</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.
 
=={{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|Julia}}==
<langsyntaxhighlight lang="julia">"""
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see
how often we had heads on waking Sleeping Beauty.
Line 167 ⟶ 588:
end
 
# If tails, we do this again, but addof onlycourse ifwe tails, so dowill not add as if it was heads.
if coin_result == "tails"
wakenings += 1
Line 186 ⟶ 607:
CREDENCE = sleeping_beauty_experiment(1_000_000)
println("Results of experiment: Sleeping Beauty should estimate a credence of: ", CREDENCE)
</langsyntaxhighlight>{{out}}<pre>
Wakenings over 1000000 experiments: 1499534
Results of experiment: Sleeping Beauty should estimate a credence of: 0.33374768428058316
</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">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]</syntaxhighlight>
{{out}}
<pre>Wakenings over 1000000 experiments: 1499714
Results of experiment: Sleeping Beauty should estimate a credence of: 0.333588</pre>
 
=={{header|Nim}}==
<syntaxhighlight lang="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</syntaxhighlight>
 
{{out}}
<pre>Wakenings over 1000000 experiments: 1499971
Sleeping Beauty should estimate a credence of: 0.3333591116094911</pre>
 
=={{header|Pascal}}==
{{trans|Phix}}
<syntaxhighlight lang="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.</syntaxhighlight>
{{out}}
<pre>Wakings over 1000000 repetitions = 1499741
Percentage probability of heads on waking = 33.35636%</pre>
 
=={{header|Perl}}==
<syntaxhighlight lang="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);</syntaxhighlight>
{{out}}
<pre>Wakenings over 1000000 experiments: 1499816
Sleeping Beauty should estimate a credence of: 0.333</pre>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="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: #000000;">fmt</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"""
Line 205 ⟶ 723:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<small>(You'll get the exact result less than 1% of the time!!)</small>
Line 215 ⟶ 733:
=={{header|Python}}==
===Procedural===
<langsyntaxhighlight lang="python">from random import choice
 
def sleeping_beauty_experiment(repetitions):
Line 232 ⟶ 750:
gotheadsonwaking += 1
 
# If tails, we do this again, but addof onlycourse ifwe tails, so dowill not add as if it was heads..
if coin_result == "tails":
wakenings += 1
Line 249 ⟶ 767:
CREDENCE = sleeping_beauty_experiment(1_000_000)
print("Results of experiment: Sleeping Beauty should estimate a credence of:", CREDENCE)
</langsyntaxhighlight>{{out}}<pre>
Wakenings over 1000000 experiments: 1499765
Results of experiment: Sleeping Beauty should estimate a credence of: 0.333542254953276
Line 257 ⟶ 775:
===Functional===
 
<langsyntaxhighlight lang="python">'''Sleeping Beauty Problem'''
 
from random import choice
Line 316 ⟶ 834:
if __name__ == '__main__':
main()
</syntaxhighlight>
</lang>
{{Out}}
<pre>1500188 wakenings over 1000000 experiments.
Line 322 ⟶ 840:
Sleeping Beauty should estimate credence
at around 0.333</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="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</syntaxhighlight>
 
{{out}}
 
<pre>Number of trials: 1000000
Data: heads count: 500212
sleeps count: 1500212
Credence of heads: 0.33342754224069664821
or approximately: 1/3
</pre>
 
=={{header|R}}==
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
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))</syntaxhighlight>
{{out}}
<pre>[1] 0.3335838</pre>
 
=={{header|Raku}}==
 
<syntaxhighlight lang="raku" perl6line>sub sleeping-beauty ($trials) {
my $gotheadsonwaking = 0;
my $wakenings = 0;
Line 339 ⟶ 905:
}
 
say "Results of experiment: Sleeping Beauty should estimate a credence of: ", sleeping-beauty(1_000_000);</langsyntaxhighlight>
{{out}}
<pre>Wakenings over 1000000 experiments: 1500040
Results of experiment: Sleeping Beauty should estimate a credence of: 0.333298</pre>
 
=={{header|Red}}==
<syntaxhighlight lang="rebol">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]</syntaxhighlight>
{{out}}
<pre>
Awakenings over 1000000 experiments: 1500063
Probability of heads on waking: 0.3332773356852345
</pre>
 
=={{header|REXX}}==
When using Regina REXX, &nbsp; the seed specified &nbsp; (for '''random''') &nbsp; was &nbsp; '''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*/
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 ?</syntaxhighlight>
{{out|output|text=&nbsp; when using the input of: &nbsp; &nbsp; <tt> , &nbsp; 46 </tt>}}
<pre>
Wakenings over 1,000,000 repetitions: 1,500,000
The percentage probability of heads on awakening: 33.3333333%
</pre>
 
=={{header|Ruby}}==
{{trans|Python}}
<syntaxhighlight lang="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)}"
</syntaxhighlight>
{{out}}
<pre>Wakenings over 1000000 experiments: 1499604
Results of experiment: Sleeping Beauty should estimate
a credence of: 0.3336854262858728
</pre>
=={{header|Swift}}==
<syntaxhighlight lang="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))")</syntaxhighlight>
 
{{out}}
<pre>
Wakenings over 1000000 experiments: 1500036
Sleeping Beauty should estimate a credence of: 0.3333013341013149
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="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%")
}</syntaxhighlight>
 
{{out}}
Sample run:
<pre>
Wakings over 1000000 repetitions = 1500224
Percentage probability of heads on waking = 33.31342519517085%
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
import "./fmt" for Fmt
 
var rand = Random.new()
Line 368 ⟶ 1,052:
 
var pc = sleepingBeauty.call(1e6)
Fmt.print("Percentage probability of heads on waking = $f\%", pc)</langsyntaxhighlight>
 
{{out}}
Line 375 ⟶ 1,059:
Wakings over 1,000,000 repetitions = 1,500,321
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>
1,995

edits