Average loop length: Difference between revisions

added Easylang
(added Easylang)
 
(18 intermediate revisions by 9 users not shown)
Line 40:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F ffactorial(n)
V result = 1.0
L(i) 2..n
Line 67:
V theory = analytical(n)
V diff = (avg / theory - 1) * 100
print(‘#2 #3.4 #3.4 #2.3%’.format(n, avg, theory, diff))</langsyntaxhighlight>
 
{{out}}
Line 96:
 
=={{header|Ada}}==
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Generic_Elementary_Functions;
with Ada.Numerics.Discrete_Random;
Line 148:
Put(err, Fore=>3, Aft=>3, exp=>0); New_line;
end loop;
end Avglen;</langsyntaxhighlight>
{{out}}
<pre>
Line 175:
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> @% = &2040A
MAX_N = 20
TIMES = 1000000
Line 207:
DEF FNfactorial(n)
IF n=1 OR n=0 THEN =1 ELSE = n * FNfactorial(n-1)</langsyntaxhighlight>
{{out}}
<pre>
Line 234:
=={{header|C}}==
 
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 289:
}
return 0;
}</langsyntaxhighlight>
{{out}}
<pre>
Line 318:
=={{header|C sharp|C#}}==
{{trans|Java}}
<langsyntaxhighlight lang="csharp">public class AverageLoopLength {
private static int N = 100000;
Line 368:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 398:
=={{header|C++}}==
Partial translation of C using stl and std.
<langsyntaxhighlight lang="cpp">#include <random>
#include <random>
#include <vector>
#include <iostream>
Line 414 ⟶ 415:
int randint(int n) {
int r, rmax = RAND_MAX / n * n;
dis=std::uniform_int_distribution<int>(0,rmax) ;
r = dis(gen);
return r / (RAND_MAX / n);
}
 
unsigned long long factorial(size_t n) {
//Factorial using dynamic programming to memoize the values.
static std::vector<unsigned long long>factorials{1,1,2};
for (;factorials.size() <= n;)
factorials.push_back(((unsigned long long) factorials.back())*factorials.size());
return factorials[n];
}
Line 460 ⟶ 461:
return 0;
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
n avg exp. diff
-------------------------------
1 1.0000 1.0000 0.000002%
2 1.49984999 1.5000 -0.016006%
3 1.88838897 1.8889 - 0.032042%
4 2.21882177 2.2188 -0.000046%
5 2.51055109 2.5104 0.004018%
6 2.77607768 2.7747 0.047077%
7 3.01800187 3.0181 - 0.004019%
8 3.2448 3.2450 -0.007008%
9 3.45804600 3.4583 - 0.010049%
10 3.66146619 3.6602 0.032046%
11 3.85328526 3.8524 0.022006%
12 4.03490391 4.0361 - 0.029076%
13 4.21532129 4.2123 0.070012%
14 4.38193858 4.3820 - 0.003087%
15 4.54945469 4.5458 0.079023%
16 4.70827045 4.7043 0.084006%
17 4.85768587 4.8579 - 0.005016%
18 5.00280071 5.0071 - 0.084001%
19 5.14841529 5.1522 - 0.073013%
20 5.29392931 5.2936 -0.006010%
 
</pre>
Line 490 ⟶ 491:
=={{header|Clojure}}==
{{trans|Python}}
<langsyntaxhighlight lang="lisp">(ns cyclelengths
(:gen-class))
 
Line 534 ⟶ 535:
diff (Math/abs (* 100 (- 1 (/ avg anal))))]]
(println (format "%3d\t%.4f\t%.4f\t%.2f%%" q avg anal diff)))
</syntaxhighlight>
</lang>
{{Output}}
<pre>
Line 562 ⟶ 563:
=={{header|D}}==
{{trans|Raku}}
<langsyntaxhighlight lang="d">import std.stdio, std.random, std.math, std.algorithm, std.range, std.format;
 
real analytical(in int n) pure nothrow @safe /*@nogc*/ {
Line 602 ⟶ 603:
n, average, an, errorS);
}
}</langsyntaxhighlight>
{{out}}
<pre> n average analytical (error)
Line 650 ⟶ 651:
{{libheader| System.Math}}
{{Trans|C}}
<syntaxhighlight lang="delphi">
<lang Delphi>
program Average_loop_length;
 
Line 717 ⟶ 718:
end.
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 745 ⟶ 746:
20 5,2960 5,2936 0,046%
</pre>
=={{header|EasyLang}}==
{{trans|Lua}}
<syntaxhighlight>
func average n reps .
for r to reps
f[] = [ ]
for i to n
f[] &= randint n
.
seen[] = [ ]
len seen[] n
x = 1
while seen[x] = 0
seen[x] = 1
x = f[x]
count += 1
.
.
return count / reps
.
func analytical n .
s = 1
t = 1
for i = n - 1 downto 1
t = t * i / n
s += t
.
return s
.
print " N average analytical (error)"
print "=== ======= ========== ======="
for n to 20
avg = average n 1e6
ana = analytical n
err = (avg - ana) / ana * 100
numfmt 0 2
write n
numfmt 4 9
print avg & ana & err & "%"
.
</syntaxhighlight>
 
=={{header|EchoLisp}}==
<langsyntaxhighlight lang="scheme">
(lib 'math) ;; Σ aka (sigma f(n) nfrom nto)
Line 776 ⟶ 819:
(define fa (f-anal N))
(printf "%3d %10d %10d %10.2d %%" N fc fa (// (abs (- fa fc)) fc 0.01))))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 805 ⟶ 848:
{{trans|Ruby}}
{{works with|Elixir|1.1+}}
<langsyntaxhighlight lang="elixir">defmodule RC do
def factorial(0), do: 1
def factorial(n), do: Enum.reduce(1..n, 1, &(&1 * &2))
Line 830 ⟶ 873:
 
runs = 1_000_000
RC.task(runs)</langsyntaxhighlight>
 
{{out}}
Line 861 ⟶ 904:
{{trans|Scala}}
<p>But uses the Gamma function instead of factorials.</p>
<langsyntaxhighlight lang="fsharp">open System
 
let gamma z =
Line 910 ⟶ 953:
printfn "%2i %2.6f %2.6f %+2.3f%%" n avg theory ((avg / theory - 1.) * 100.))
0
</syntaxhighlight>
</lang>
{{out}}
<pre> N average analytical (error)
Line 938 ⟶ 981:
The <code>loop-length</code> word is more or less a translation of the inner loop of C's <code>test</code> function.
{{works with|Factor|0.99 2020-01-23}}
<langsyntaxhighlight lang="factor">USING: formatting fry io kernel locals math math.factorials
math.functions math.ranges random sequences ;
 
Line 962 ⟶ 1,005:
 
" n\tavg\texp.\tdiff\n-------------------------------" print
20 [1,b] [ .line ] each</langsyntaxhighlight>
{{out}}
<pre>
Line 991 ⟶ 1,034:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">Const max_N = 20, max_ciclos = 1000000
 
Function Factorial(Byval N As Integer) As Double
Line 1,034 ⟶ 1,077:
Next N
Sleep
</syntaxhighlight>
</lang>
 
 
=={{header|FutureBasic}}==
<langsyntaxhighlight lang="futurebasic">
_nmax = 20
_times = 1000000
Line 1,050 ⟶ 1,093:
while ( b and x ) == 0
c++
b = b or|| x
x = 1 << ( rnd(n) - 1 )
wend
Line 1,088 ⟶ 1,131:
 
HandleEvents
</syntaxhighlight>
</lang>
{{output}}
<pre>
Line 1,118 ⟶ 1,161:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,161 ⟶ 1,204:
}
return sum
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,189 ⟶ 1,232:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import System.Random
import qualified Data.Set as S
import Text.Printf
Line 1,242 ⟶ 1,285:
range = [1..20] :: [Integer]
_ <- test samples range $ mkStdGen 0
return ()</langsyntaxhighlight>
<pre> N average analytical (error)
=== ========= ============ =========
Line 1,272 ⟶ 1,315:
 
We can implement f as {&LIST where LIST is an arbitrary list of N numbers, each picked independently from the range 0..(N-1). We can incrementally build the described sequence using (, f@{:) - here we extend the sequence by applying f to the last element of the sequence. Since we are only concerned with the sequence up to the point of the first repeat, we can select the unique values giving us (~.@, f@{:). This routine stops changing when we reach the desired length, so we can repeatedly apply it forever. For example:
<langsyntaxhighlight Jlang="j"> (~.@, {&0 0@{:)^:_] 0
0
(~.@, {&0 0@{:)^:_] 1
1 0</langsyntaxhighlight>
Once we have the sequence, we can count how many elements are in it.
<langsyntaxhighlight Jlang="j"> 0 0 ([: # (] ~.@, {:@] { [)^:_) 1
2</langsyntaxhighlight>
Meanwhile, we can also generate all possible values of 1..N by counting out N^N values and breaking out the result as a base N list of digits.
<langsyntaxhighlight Jlang="j"> (#.inv i.@^~)2
0 0
0 1
1 0
1 1</langsyntaxhighlight>
All that's left is to count the lengths of all possible sequences for all possible distinct instances of f and average the results:
<langsyntaxhighlight Jlang="j"> (+/ % #)@,@((#.inv i.@^~) ([: # (] ~.@, {:@] { [)^:_)"1 0/ i.)1
1
(+/ % #)@,@((#.inv i.@^~) ([: # (] ~.@, {:@] { [)^:_)"1 0/ i.)2
Line 1,297 ⟶ 1,340:
2.5104
(+/ % #)@,@((#.inv i.@^~) ([: # (] ~.@, {:@] { [)^:_)"1 0/ i.)6
2.77469</langsyntaxhighlight>
Meanwhile the analytic solution (derived by reading the Ada implementation) looks like this:
<langsyntaxhighlight Jlang="j"> ana=: +/@(!@[ % !@- * ^) 1+i.
ana"0]1 2 3 4 5 6
1 1.5 1.88889 2.21875 2.5104 2.77469</langsyntaxhighlight>
To get our simulation, we can take the exact approach and replace the part that generates all possible values for f with a random mechanism. Since the task does not specify how long to run the simulation, and to make this change easy, we'll use N*1e4 tests.
<langsyntaxhighlight Jlang="j"> sim=: (+/ % #)@,@((]?@$~1e4,]) ([: # (] ~.@, {:@] { [)^:_)"1 0/ i.)
sim"0]1 2 3 4 5 6
1 1.5034 1.8825 2.22447 2.51298 2.76898</langsyntaxhighlight>
The simulation approach is noticeably slower than the analytic approach, while being less accurate.
 
Finally, we can generate our desired results:
<langsyntaxhighlight Jlang="j"> (;:'N average analytic error'),:,.each(;ana"0 ([;];-|@%[) sim"0)1+i.20
+--+-------+--------+-----------+
|N |average|analytic|error |
Line 1,333 ⟶ 1,376:
|19| 5.1522|5.14785 |0.000843052|
|20|5.29358|5.28587 | 0.00145829|
+--+-------+--------+-----------+</langsyntaxhighlight>
Here, error is the difference between the two values divided by the analytic value.
 
Line 1,340 ⟶ 1,383:
This uses a 0-based index (0, 1, ..., n-1) as opposed to the 1-based index (1, 2, ..., n) specified in the question, because it fits better with the native structure of Java.
 
<langsyntaxhighlight lang="java">import java.util.HashSet;
import java.util.Random;
import java.util.Set;
Line 1,395 ⟶ 1,438:
}
}
}</langsyntaxhighlight>
 
=={{header|Julia}}==
{{trans|Python}}
<langsyntaxhighlight lang="julia">using Printf
 
analytical(n::Integer) = sum(factorial(n) / big(n) ^ i / factorial(n - i) for i = 1:n)
Line 1,427 ⟶ 1,470:
 
main(20)
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,457 ⟶ 1,500:
=={{header|Kotlin}}==
{{trans|Go}}
<langsyntaxhighlight lang="scala">const val NMAX = 20
const val TESTS = 1000000
val rand = java.util.Random()
Line 1,494 ⟶ 1,537:
println(String.format("%3d %6.4f %10.4f (%4.2f%%)", n, a, b, Math.abs(a - b) / b * 100.0))
}
}</langsyntaxhighlight>
Sample output:
{{out}}
Line 1,524 ⟶ 1,567:
=={{header|Liberty BASIC}}==
{{trans|BBC BASIC}}
<syntaxhighlight lang="lb">
<lang lb>
MAXN = 20
TIMES = 10000'00
Line 1,561 ⟶ 1,604:
IF n=1 OR n=0 THEN FNfactorial=1 ELSE FNfactorial= n * FNfactorial(n-1)
end function
</syntaxhighlight>
</lang>
 
{{out}}
Line 1,588 ⟶ 1,631:
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">function average(n, reps)
local count = 0
for r = 1, reps do
Line 1,613 ⟶ 1,656:
local err = (avg-ana) / ana * 100
print(string.format("%3d %9.4f %12.4f (%6.3f%%)", n, avg, ana, err))
end</langsyntaxhighlight>
{{out}}
<pre> N average analytical (error)
Line 1,639 ⟶ 1,682:
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">Grid@Prepend[
Table[{n, #[[1]], #[[2]],
Row[{Round[10000 Abs[#[[1]] - #[[2]]]/#[[2]]]/100., "%"}]} &@
Line 1,647 ⟶ 1,690:
RandomInteger[{1, n}, n]] &] &, 10000]],
Sum[n! n^(n - k - 1)/(n - k)!, {k, n}]/n^(n - 1)}, 5], {n, 1,
20}], {"N", "average", "analytical", "error"}]</langsyntaxhighlight>
{{Out}}
<pre>N average analytical error
Line 1,673 ⟶ 1,716:
=={{header|Nim}}==
{{trans|C}}
<langsyntaxhighlight lang="nim">import random, math, strformat
randomize()
Line 1,706 ⟶ 1,749:
let theory = expected(n)
let diff = (avg / theory - 1) * 100
echo fmt"{n:2} {avg:8.4f} {theory:8.4f} {diff:6.3f}%"</langsyntaxhighlight>
{{out}}
<pre> n avg exp. diff
Line 1,732 ⟶ 1,775:
 
=={{header|Oberon-2}}==
<langsyntaxhighlight lang="oberon2">
MODULE AvgLoopLen;
(* Oxford Oberon-2 *)
Line 1,804 ⟶ 1,847:
END
END AvgLoopLen.
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,832 ⟶ 1,875:
=={{header|PARI/GP}}==
{{trans|C}}
<langsyntaxhighlight lang="parigp">expected(n)=sum(i=1,n,n!/(n-i)!/n^i,0.);
test(n, times)={
my(ct);
Line 1,845 ⟶ 1,888:
my(cnt=test(n, TIMES),avg=cnt/TIMES,ex=expected(n),diff=(avg/ex-1)*100.);
print(n"\t"avg*1."\t"ex*1."\t"diff);
)}</langsyntaxhighlight>
{{out}}
<pre>1 1.0000 1.0000 0.E-7
Line 1,869 ⟶ 1,912:
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use List::Util qw(sum reduce);
 
sub find_loop {
Line 1,889 ⟶ 1,932:
printf "%3d %9.4f %12.4f (%5.2f%%)\n",
$n, $empiric, $theoric, 100 * ($empiric - $theoric) / $theoric;
}</langsyntaxhighlight>
{{out}}
<pre> N empiric theoric (error)
Line 1,915 ⟶ 1,958:
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">constant</span> <span style="color: #000000;">MAX</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">20</span><span style="color: #0000FF;">,</span>
<span style="color: #000000;">ITER</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1000000</span>
Line 1,949 ⟶ 1,992:
<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;">"%2d %8.4f %8.4f (%5.3f%%)\n"</span><span style="color: #0000FF;">,</span> <span style="color: #0000FF;">{</span><span style="color: #000000;">n</span><span style="color: #0000FF;">,</span><span style="color: #000000;">av</span><span style="color: #0000FF;">,</span><span style="color: #000000;">ex</span><span style="color: #0000FF;">,</span><span style="color: #7060A8;">abs</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">-</span><span style="color: #000000;">av</span><span style="color: #0000FF;">/</span><span style="color: #000000;">ex</span><span style="color: #0000FF;">)*</span><span style="color: #000000;">100</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,978 ⟶ 2,021:
=={{header|Phixmonti}}==
{{trans|Phix}}
<langsyntaxhighlight Phixmontilang="phixmonti">include ..\Utilitys.pmt
 
20 var MAX
Line 2,019 ⟶ 2,062:
n expected
n rot rot over over / 1 swap - abs 100 * 4 tolist printAll drop nl
endfor</langsyntaxhighlight>
{{out}}
<pre>n avg. exp. (error%)
Line 2,048 ⟶ 2,091:
=={{header|PicoLisp}}==
{{trans|Python}}
<langsyntaxhighlight PicoLisplang="picolisp">(scl 4)
(seed (in "/dev/urandom" (rd 8)))
 
Line 2,089 ⟶ 2,132:
2 ) ) ) ) )
 
(bye)</langsyntaxhighlight>
 
=={{header|PowerShell}}==
{{works with|PowerShell|2}}
<syntaxhighlight lang="powershell">
<lang PowerShell>
function Get-AnalyticalLoopAverage ( [int]$N )
{
Line 2,153 ⟶ 2,196:
return $LoopAvereage
}
</syntaxhighlight>
</lang>
Note: The use of the [pscustomobject] type accelerator to simplify making the test result table look pretty requires PowerShell 3.0.
<syntaxhighlight lang="powershell">
<lang PowerShell>
# Display results for N = 1 through 20
ForEach ( $N in 1..20 )
Line 2,168 ⟶ 2,211:
}
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,197 ⟶ 2,240:
=={{header|Python}}==
{{trans|C}}
<langsyntaxhighlight lang="python">from __future__ import division # Only necessary for Python 2.X
from math import factorial
from random import randrange
Line 2,223 ⟶ 2,266:
theory = analytical(n)
diff = (avg / theory - 1) * 100
print("%2d %8.4f %8.4f %6.3f%%" % (n, avg, theory, diff))</langsyntaxhighlight>
{{out}}
<pre> n avg exp. diff
Line 2,247 ⟶ 2,290:
19 5.1534 5.1522 0.024%
20 5.2927 5.2936 -0.017%</pre>
 
=={{header|Quackery}}==
 
<syntaxhighlight lang="Quackery"> [ $ "bigrat.qky" loadfile ] now!
 
[ tuck space swap of
join
swap split drop echo$ ] is lecho$ ( $ n --> )
 
[ 1 swap times [ i 1+ * ] ] is ! ( n --> n )
 
[ 0 n->v rot
dup temp put
times
[ temp share ! n->v
temp share i 1+ - ! n->v
v/
temp share i 1+ ** n->v
v/ v+ ]
temp release ] is expected ( n --> n/d )
 
[ -1 temp put
0
[ 1 temp tally
over random bit
2dup & not while
| again ]
2drop drop
temp take ] is trial ( n --> n )
 
[ tuck 0 swap
times
[ over trial + ]
nip swap reduce ] is trials ( n n --> n/d )
 
[ say " n average expected difference"
cr
say "-- ------- -------- ----------"
cr
20 times
[ i^ 1+ dup 10 < if sp echo
2 times sp
i^ 1+ 1000000 trials
2dup 7 point$ 10 lecho$
i^ 1+ expected
2dup 7 point$ 11 lecho$
v/ 1 n->v v- 100 1 v* vabs
7 point$ echo$ say "%" cr ] ] is task ( --> )</syntaxhighlight>
 
{{out}}
 
<pre> n average expected difference
-- ------- -------- ----------
1 1 1 0%
2 1.499195 1.5 0.0536667%
3 1.88936 1.8888889 0.0249412%
4 2.220728 2.21875 0.0891493%
5 2.508183 2.5104 0.0883126%
6 2.773072 2.7746914 0.0583617%
7 3.019331 3.0181387 0.0395045%
8 3.243534 3.245018 0.0457318%
9 3.45625 3.4583157 0.0597327%
10 3.658848 3.6602157 0.0373661%
11 3.850874 3.8523721 0.0388865%
12 4.032375 4.0360737 0.0916404%
13 4.212238 4.2123479 0.0026093%
14 4.383076 4.3820294 0.0238834%
15 4.544029 4.5458073 0.0391192%
16 4.706797 4.7042582 0.0539671%
17 4.856011 4.8578708 0.0382847%
18 5.004107 5.0070631 0.0590386%
19 5.152561 5.1521962 0.0070805%
20 5.288056 5.2935846 0.1044394%
</pre>
 
=={{header|R}}==
<syntaxhighlight lang="r">
<lang R>
expected <- function(size) {
result <- 0
Line 2,284 ⟶ 2,401:
cat(sprintf("%3d%11.4f%14.4f ( %4.4f%%)\n", num, round(average,4), round(analytical,4), round(error,2)))
}
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,313 ⟶ 2,430:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require (only-in math factorial))
Line 2,341 ⟶ 2,458:
 
(test-table 20 10000)
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,371 ⟶ 2,488:
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>constant MAX_N = 20;
{{Works with|rakudo|2016.08}}
<lang perl6>constant MAX_N = 20;
constant TRIALS = 100;
for 1 .. MAX_N -> $N {
my $empiric = TRIALS R/ [+] find-loop(random-mapping( $N)).elems xx TRIALS;
my $theoric = [+]
map -> $k { $N ** ($k + 1) R/ [*×] flat $k**2, $N - $k + 1 .. $N }, 1 .. $N;
FIRST say " N empiric theoric (error)";
Line 2,384 ⟶ 2,500:
printf "%3d %9.4f %12.4f (%4.2f%%)\n",
$N, $empiric, $theoric, 100 × abs($theoric - $empiric) / $theoric;
$theoric, 100 * abs($theoric - $empiric) / $theoric;
}
sub random-mapping { hash .list Z=> .roll($_) given ^$^size }
sub find-loop { 0, | %^mapping{*} ...^ { (%){$_}++ } }</langsyntaxhighlight>
{{out|Example}}
<pre> N empiric theoric (error)
Line 2,419 ⟶ 2,534:
 
Also note that the &nbsp; <big>'''!'''</big> &nbsp; (factorial function) &nbsp; uses memoization for optimization.
<langsyntaxhighlight lang="rexx">/*REXX program computes the average loop length mapping a random field 1···N ───► 1···N */
parse arg runs tests seed . /*obtain optional arguments from the CL*/
if runs =='' | runs =="," then runs = 40 /*Not specified? Then use the default.*/
Line 2,454 ⟶ 2,569:
/*──────────────────────────────────────────────────────────────────────────────────────*/
fmtD: parse arg y,d; d=word(d 4, 1); y=format(y, , d); parse var y w '.' f
if f=0 then return w || left('', d +1); return y</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default inputs:}}
<pre style="height:90ex">
Line 2,504 ⟶ 2,619:
40 7.6151 7.6091 0.0789
═══ ═════════ ═════════ ═════════
</pre>
 
=={{header|RPL}}==
This task is an opportunity to showcase several useful instructions - <code>CON, SEQ</code> and <code>∑</code> - which avoid to use a <code>FOR..NEXT</code> loop, to create a constant array, to generate a list of random numbers and to calculate a finite sum.
{{works with|HP|48G}}
« 0 → n times count
« 1 times '''FOR''' j
n { } + 0 CON
« n RAND * CEIL » 'z' 1 n 1 SEQ
1
'''WHILE''' 3 PICK OVER GET NOT '''REPEAT'''
ROT OVER 1 PUT ROT ROT
OVER SWAP GET
'count' 1 STO+
'''END''' 3 DROPN
'''NEXT'''
count times /
» » '<span style="color:blue">XPRMT</span>' STO
« { } DUP
1 20 '''FOR''' n
SWAP n 1000 <span style="color:blue">XPRMT</span> +
SWAP 'j' 1 n 'n!/n^j/(n-j)!' ∑ +
'''NEXT'''
DUP2 SWAP %CH ABS 2 FIX "%" ADD STD
» '<span style="color:blue">TASK</span>' STO
{{out}}
<pre>
3: { 1 1.497 1.882 2.2 2.468 2.823 3 3.258 3.475 3.647 3.854 4.003 4.234 4.46 4.589 4.767 4.852 4.929 5.154 5.251 }
2: { 1 1.5 1.88888888889 2.21875 2.5104 2.77469135802 3.0181387007 3.24501800538 3.45831574488 3.66021568 3.85237205073 4.03607367511 4.21234791298 4.38202942438 4.54580728514 4.70425824709 4.85787082081 5.00706309901 5.15219620097 5.29358458601 }
1:{ "0.00%" "0.20%" "0.36%" "0.85%" "1.69%" "1.74%" "0.60%" "0.40%" "0.48%" "0.36%" "0.04%" "0.82%" "0.51%" "1.78%" "0.95%" "1.33%" "0.12%" "1.56%" "0.04%" "0.80%" }
</pre>
 
=={{header|Ruby}}==
Ruby does not have a factorial method, not even in it's math library.
<langsyntaxhighlight lang="ruby">class Integer
def factorial
self == 0 ? 1 : (1..self).inject(:*)
Line 2,532 ⟶ 2,678:
analytical = (1..n).inject(0){|sum, i| sum += (n.factorial / (n**i).to_f / (n-i).factorial)}
puts "%3d %8.4f %8.4f (%8.4f%%)" % [n, avg, analytical, (avg/analytical - 1)*100]
end</langsyntaxhighlight>
{{out}}
<pre>
Line 2,561 ⟶ 2,707:
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">extern crate rand;
 
use rand::{ThreadRng, thread_rng};
Line 2,637 ⟶ 2,783:
 
 
</syntaxhighlight>
</lang>
{{out}}
Using default arguments:
Line 2,667 ⟶ 2,813:
=={{header|Scala}}==
 
<syntaxhighlight lang="scala">
<lang Scala>
import scala.util.Random
 
Line 2,704 ⟶ 2,850:
 
}
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,733 ⟶ 2,879:
=={{header|Scheme}}==
 
<langsyntaxhighlight lang="scheme">
(import (scheme base)
(scheme write)
Line 2,790 ⟶ 2,936:
(newline)))
(iota 20 1))
</syntaxhighlight>
</lang>
 
{{out}}
Line 2,819 ⟶ 2,965:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "float.s7i";
 
Line 2,882 ⟶ 3,028:
analytical digits 4 lpad 7 <& err digits 3 lpad 7);
end for;
end func;</langsyntaxhighlight>
 
{{out}}
Line 2,911 ⟶ 3,057:
=={{header|Sidef}}==
{{trans|Perl}}
<langsyntaxhighlight lang="ruby">func find_loop(n) {
var seen = Hash()
loop {
Line 2,932 ⟶ 3,078:
printf("%3d %9.4f %12.4f (%5.2f%%)\n",
n, empiric, theoric, 100*(empiric-theoric)/theoric)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,960 ⟶ 3,106:
 
=={{header|Simula}}==
<langsyntaxhighlight lang="simula">BEGIN
 
REAL PROCEDURE FACTORIAL(N); INTEGER N;
Line 3,024 ⟶ 3,170:
END FOR I;
END;
END</langsyntaxhighlight>
{{in}}
<pre>678</pre>
Line 3,051 ⟶ 3,197:
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl"># Generate a list of the numbers increasing from $a to $b
proc range {a b} {
for {set result {}} {$a <= $b} {incr a} {lappend result $a}
Line 3,090 ⟶ 3,236:
set e [Experimental $n 100000]
puts [format "%3d %9.4f %12.4f (%6.2f%%)" $n $e $a [expr {abs($e-$a)/$a*100.0}]]
}</langsyntaxhighlight>
{{out}}
<pre>
Line 3,116 ⟶ 3,262:
20 5.2992 5.2936 ( 0.11%)
</pre>
 
=={{header|uBasic/4tH}}==
{{trans|BBC BASIC}}
This is about the limit of what you can do with uBasic/4tH. Since it is an integer BASIC, it uses what has become known in the Forth community as "Brodie math". The last 14 bits of an 64-bit integer are used to represent the fraction, so basically it is a form of "fixed point math". This, of course, leads inevitably to rounding errors. After step 14 the number is too large to fit in a 64-bit integer - so at that point it simply breaks down. Performance is another issue.
 
<syntaxhighlight lang="uBasic/4tH">M = 14
T = 100000
 
If Info("wordsize") < 64 Then Print "This program requires a 64-bit uBasic" : End
 
Print "N\tavg\tcalc\t%diff"
 
For n = 1 To M
a = FUNC(_Test(n, T))
h = FUNC(_Analytical(n))
d = FUNC(_Fmul(FUNC(_Fdiv(a, h)) - FUNC(_Ntof(1)), FUNC(_Ntof(100))))
 
Print n; "\t";
Proc _Fprint (a) : Print "\t";
Proc _Fprint (h) : Print "\t";
Proc _Fprint (d) : Print "%"
Next
End
 
_Analytical
Param (1)
Local (3)
 
c@ = 0
For b@ = 1 To a@
d@ = FUNC(_Fdiv(FUNC(_Factorial(a@)), a@^b@))
c@ = c@ + FUNC(_Fdiv (d@, FUNC(_Ntof(FUNC(_Factorial(a@-b@))))))
Next
Return (c@)
 
_Test
Param (2)
Local (4)
 
e@ = 0
For c@ = 1 To b@
f@ = 1 : d@ = 0
Do While AND(d@, f@) = 0
e@ = e@ + 1
d@ = OR(d@, f@)
f@ = SHL(1, Rnd(a@))
Loop
Next
Return (FUNC(_Fdiv(e@, b@)))
 
_Factorial
Param(1)
 
If (a@ = 1) + (a@ = 0) Then Return (1)
Return (a@ * FUNC(_Factorial(a@-1)))
 
_Fmul Param (2) : Return ((a@*b@)/16384)
_Fdiv Param (2) : Return ((a@*16384)/b@)
_Ftoi Param (1) : Return ((10000*a@)/16384)
_Itof Param (1) : Return ((16384*a@)/10000)
_Ntof Param (1) : Return (16384*a@)
_Fprint Param (1) : a@ = FUNC(_Ftoi(a@)) : Print Using "+?.####";a@; : Return</syntaxhighlight>
{{Out}}
<pre>N avg calc %diff
1 1.0000 1.0000 0.0000%
2 1.4985 1.5000 -0.0976%
3 1.8869 1.8887 -0.1037%
4 2.2192 2.2187 0.0183%
5 2.5130 2.5103 0.1037%
6 2.7761 2.7745 0.0549%
7 3.0264 3.0180 0.2746%
8 3.2504 3.2449 0.1647%
9 3.4528 3.4581 -0.1525%
10 3.6651 3.6599 0.1403%
11 3.8543 3.8521 0.0549%
12 4.0364 4.0357 0.0122%
13 4.2153 4.2119 0.0793%
14 4.3866 4.3815 0.1098%
 
0 OK, 0:392</pre>
 
=={{header|Unicon}}==
{{trans|C}}
<langsyntaxhighlight lang="unicon">link printf, factors
 
$define MAX_N 20
Line 3,157 ⟶ 3,383:
}
return 0
end</langsyntaxhighlight>
{{out}}
<pre> n avg exp. diff
Line 3,184 ⟶ 3,410:
=={{header|VBA}}==
{{trans|Phix}}
<langsyntaxhighlight lang="vb">Const MAX = 20
Const ITER = 1000000
Line 3,220 ⟶ 3,446:
Debug.Print Format(ex, "0.0000"); " ("; Format(Abs(1 - av / ex), "0.000%"); ")"
Next n
End Sub</langsyntaxhighlight>{{out}}
<pre> n avg. exp. (error%)
== ====== ====== ========
Line 3,246 ⟶ 3,472:
=={{header|VBScript}}==
Ported from the VBA version. I added some precalculations to speed it up
<syntaxhighlight lang="vb">
<lang vb>
Const MAX = 20
Const ITER = 100000
Line 3,295 ⟶ 3,521:
rf(formatnumber(ex,4),6," ")& " ("& rf(Formatpercent(1 - av / ex,4),8," ") & ")"
Next
</syntaxhighlight>
</lang>
Output
<pre>
Line 3,323 ⟶ 3,549:
</pre>
 
=={{header|V (Vlang)}}==
{{trans|Go}}
<syntaxhighlight lang="v (vlang)">import rand
import math
 
Line 3,363 ⟶ 3,589:
}
return sum
}</langsyntaxhighlight>
 
{{out}}
Line 3,395 ⟶ 3,621:
{{trans|Go}}
{{libheader|Wren-fmt}}
<langsyntaxhighlight ecmascriptlang="wren">import "random" for Random
import "./fmt" for Fmt
 
var nmax = 20
Line 3,432 ⟶ 3,658:
var a = avg.call(n)
var b = ana.call(n)
var ns = Fmt.d(3, n)
var as = Fmt.f(9, a, 4)
var bs = Fmt.f(12, b, 4)
var e = (a - b).abs/ b * 100
varFmt.print("$3d es$9.4f = Fmt$12.f4f ($6.2f\%)", en, 2a, b, e)
}</syntaxhighlight>
System.print("%(ns) %(as) %(bs) (%(es)\%)")
}</lang>
 
{{out}}
Line 3,468 ⟶ 3,690:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">const N=20;
 
(" N average analytical (error)").println();
Line 3,500 ⟶ 3,722:
n=n.toFloat();
(1).reduce(n,'wrap(sum,i){ sum+fact(n)/n.pow(i)/fact(n-i) },0.0);
}</langsyntaxhighlight>
{{out}}
<pre>
2,041

edits