Jump to content

Statistics/Basic: Difference between revisions

m
syntax highlighting fixup automation
No edit summary
m (syntax highlighting fixup automation)
Line 38:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F sd_mean(numbers)
V mean = sum(numbers) / numbers.len
V sd = (sum(numbers.map(n -> (n - @mean) ^ 2)) / numbers.len) ^ 0.5
Line 59:
V (sd, mean) = sd_mean(n)
print(‘ sd: #.6, mean: #.6’.format(sd, mean))
histogram(n)</langsyntaxhighlight>
 
{{out}}
Line 102:
{{libheader|Action! Tool Kit}}
{{libheader|Action! Real Math}}
<langsyntaxhighlight Actionlang="action!">INCLUDE "H6:REALMATH.ACT"
 
DEFINE SIZE="10000"
Line 228:
PutE() PutE()
Test(10000)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Statistics_basic.png Screenshot from Atari 8-bit computer]
Line 261:
===A plain solution for moderate sample sizes===
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Float_Random,
Ada.Numerics.Generic_Elementary_Functions;
 
Line 323:
TIO.New_Line;
Put_Mean_Et_Al(Sample_Size => N, Val_Sum => Val_Sum, Square_Sum => Squ_Sum);
end Basic_Stat;</langsyntaxhighlight>
 
{{out}} from a few sample runs:
Line 399:
This is the modified program
 
<langsyntaxhighlight Adalang="ada">with Ada.Text_IO, Ada.Command_Line, Ada.Numerics.Float_Random,
Ada.Numerics.Generic_Elementary_Functions;
 
Line 475:
Put_Mean_Et_Al(Sample_Size => N,
Val_Sum => Float(Val_Sum), Square_Sum => Float(Squ_Sum));
end Long_Basic_Stat;</langsyntaxhighlight>
 
{{out}} for sample size 10^12 took one night on my PC:
Line 561:
=={{header|C}}==
Sample code.
<langsyntaxhighlight Clang="c">#include <stdio.h>
#include <stdlib.h>
#include <math.h>
Line 662:
}
}
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
{{libheader|Math.Net}}
<langsyntaxhighlight lang="csharp">using System;
using MathNet.Numerics.Statistics;
 
Line 697:
Run(10000);
}
}</langsyntaxhighlight>
{{out}}
<pre>Sample size: 100
Line 742:
 
=={{header|C++}}==
<langsyntaxhighlight Cpplang="cpp">#include <iostream>
#include <random>
#include <vector>
Line 789:
std::cout << "Standard deviation is " << stddev << " !" << std::endl ;
return 0 ;
}</langsyntaxhighlight>
{{out}}
<pre>./statistics 100
Line 805:
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript">
generate_statistics = (n) ->
hist = {}
Line 843:
display_statistics n, mean, stddev, hist
 
</syntaxhighlight>
</lang>
 
{{out}}
Line 904:
=={{header|D}}==
{{trans|Python}}
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.array, std.typecons,
std.range, std.exception;
 
Line 948:
}
}
}</langsyntaxhighlight>
Compile with "-version=statistics_basic_main" to run the main function.
{{out}}
Line 1,030:
 
=={{header|Dart}}==
<langsyntaxhighlight lang="d">/* Import math library to get:
* 1) Square root function : Math.sqrt(x)
* 2) Power function : Math.pow(base, exponent)
Line 1,128:
print('');
}
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,205:
=={{header|Elixir}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="elixir">defmodule Statistics do
def basic(n) do
{sum, sum2, hist} = generate(n)
Line 1,231:
Enum.each([100,1000,10000], fn n ->
Statistics.basic(n)
end)</langsyntaxhighlight>
 
{{out}}
Line 1,279:
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">USING: assocs formatting grouping io kernel literals math
math.functions math.order math.statistics prettyprint random
sequences sequences.deep sequences.repeating ;
Line 1,315:
{ 100 1,000 10,000 } [ stats ] each ;
MAIN: main</langsyntaxhighlight>
{{out}}
<pre>
Line 1,364:
{{works with|Fortran|95 and later}}
This version will handle numbers as large as 1 trillion or more if you are prepared to wait long enough
<langsyntaxhighlight lang="fortran">program basic_stats
implicit none
Line 1,399:
end do
end program</langsyntaxhighlight>
{{out}}
<pre>
Line 1,460:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
Randomize
Line 1,528:
Print
Print "Press any key to quit"
Sleep</langsyntaxhighlight>
 
{{out}}
Line 1,594:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,634:
}
fmt.Println()
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,684:
 
The following runs comfortably on a simulated data size of 10 million. To scale to a trillion, and to use real data, you would want to use a technique like [[Distributed_programming#Go]] to distribute work across multiple computers, and on each computer, use a technique like [[Parallel_calculations#Go]] to distribute work across multiple cores within each computer. You would tune parameters like the constant <tt>threshold</tt> in the code below to optimize cache performance.
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,747:
}
return
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,766:
 
=={{header|Haskell}}==
<langsyntaxhighlight Haskelllang="haskell">import Data.Foldable (foldl') --'
import System.Random (randomRs, newStdGen)
import Control.Monad (zipWithM_)
Line 1,834:
 
-- To avoid Wiki formatting issue
foldl'' = foldl'</langsyntaxhighlight>
{{out}}
<pre>./Statistics 100
Line 1,866:
=={{header|Hy}}==
 
<langsyntaxhighlight lang="lisp">(import
[numpy.random [random]]
[numpy [mean std]]
Line 1,876:
 
(plt.hist (random 1000))
(plt.show)</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Line 1,883:
In this example,
 
<langsyntaxhighlight Iconlang="icon">procedure main(A)
 
W := 50 # avg width for histogram bar
Line 1,908:
write(right(real(i)/*H,5)," : ",repl("*",integer(*H*50./N*H[i])))
}
end</langsyntaxhighlight>
 
{{out}}
Line 1,957:
 
J has library routines to compute mean and standard deviation:
<langsyntaxhighlight lang="j"> require 'stats'
(mean,stddev) 1000 ?@$ 0
0.484669 0.287482
Line 1,963:
0.503642 0.290777
(mean,stddev) 100000 ?@$ 0
0.499677 0.288726</langsyntaxhighlight>
 
And, for a histogram:
 
<langsyntaxhighlight lang="j">histogram=: <: @ (#/.~) @ (i.@#@[ , I.)
require'plot'
plot ((% * 1 + i.)100) ([;histogram) 10000 ?@$ 0</langsyntaxhighlight>
 
but these are not quite what is being asked for here.
Line 1,975:
Instead:
 
<langsyntaxhighlight lang="j">histogram=: <: @ (#/.~) @ (i.@#@[ , I.)
 
meanstddevP=: 3 :0
Line 1,998:
smoutput (<.300*h%y) #"0 '#'
(s%y) , %:t%y
)</langsyntaxhighlight>
 
Example use:
 
<langsyntaxhighlight lang="j"> meanstddevP 1000
#############################
####################################
Line 2,037:
##############################
#############################
0.500872 0.288241</langsyntaxhighlight>
 
(That said, note that these numbers are random, so reported standard deviation will vary with the random sample being tested.)
Line 2,046:
Translation of [[Statistics/Basic#Python|Python]] via [[Statistics/Basic#D|D]]
{{works with|Java|8}}
<langsyntaxhighlight lang="java">import static java.lang.Math.pow;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.joining;
Line 2,097:
}
}
}</langsyntaxhighlight>
<pre>10 numbers:
Mean: 0.564409, SD: 0.249601
Line 2,190:
 
For the sake of illustration, we will use /dev/urandom encapsulated in a shell function:
<langsyntaxhighlight lang="sh"># Usage: prng N width
function prng {
cat /dev/urandom | tr -cd '0-9' | fold -w "$2" | head -n "$1"
}</langsyntaxhighlight>
 
'''basicStats.jq'''
<langsyntaxhighlight lang="jq"> # $histogram should be a JSON object, with buckets as keys and frequencies as values;
# $keys should be an array of all the potential bucket names (possibly integers)
# in the order to be used for display:
Line 2,227:
stddev: \(.stddev)
Histogram dividing [0,1] into 10 equal intervals:",
pp(.histogram; [range(0;10)] )</langsyntaxhighlight>
'''Driver Script''' (e.g. bash)
<syntaxhighlight lang="text">for n in 100 1000 1000000 100000000; do
echo "Basic statistics for $n PRNs in [0,1]"
prng $n 10 | jq -nrR -f basicStats.jq
echo
done</langsyntaxhighlight>
{{out}}
<pre>
Line 2,304:
 
=={{header|Jsish}}==
<langsyntaxhighlight lang="javascript">#!/usr/bin/env jsish
"use strict";
 
Line 2,413:
0
=!EXPECTEND!=
*/</langsyntaxhighlight>
 
{{out}}
Line 2,420:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Printf
 
function hist(numbers)
Line 2,439:
@printf("μ: %8.6f; σ: %8.6f\n", mean(n), std(n))
hist(n)
end</langsyntaxhighlight>
 
{{out}}
Line 2,530:
Using the "mu" (mean) and "sd" (standard deviation) functions from the
Klong statistics library:
<syntaxhighlight lang="k">
<lang K>
.l("nstat.kg")
bar::{x{x;.d("*")}:*0;.p("")}
Line 2,540:
plot(1000)
plot(10000)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,588:
=={{header|Kotlin}}==
{{trans|FreeBASIC}}
<langsyntaxhighlight lang="scala">// version 1.1.2
 
val rand = java.util.Random()
Line 2,636:
val sampleSizes = intArrayOf(100, 1_000, 10_000, 100_000)
for (sampleSize in sampleSizes) basicStats(sampleSize)
}</langsyntaxhighlight>
Sample run:
{{out}}
Line 2,702:
 
=={{header|Lasso}}==
<langsyntaxhighlight Lassolang="lasso">define stat1(a) => {
if(#a->size) => {
local(mean = (with n in #a sum #n) / #a->size)
Line 2,752:
histogram(#n)
'\r\r'
^}</langsyntaxhighlight>
 
{{out}}
Line 2,824:
=={{header|Liberty BASIC}}==
Be aware that the PRNG in LB has a SLIGHT bias.
<syntaxhighlight lang="lb">
<lang lb>
call sample 100
call sample 1000
Line 2,866:
print
end sub
</syntaxhighlight>
</lang>
100000 data terms used.
Mean =0.49870232
Line 2,883:
=={{header|Lua}}==
The standard deviation seems to converge to around 0.28. I expect there's a good reason for this, though it's entirely beyond me.
<langsyntaxhighlight lang="lua">
math.randomseed(os.time())
 
Line 2,940:
showStats(10 ^ power)
end
</syntaxhighlight>
</lang>
 
=={{header|Maple}}==
The following samples 100 uniformly distributed numbers between 0 and 1:
<langsyntaxhighlight lang="maple">with(Statistics):
X_100 := Sample( Uniform(0,1), 100 );
Mean( X_100 );
StandardDeviation( X_100 );
Histogram( X_100 );</langsyntaxhighlight>
It is also possible to make a procedure that outputs the mean, standard deviation, and a histogram for a given number of random uniformly distributed numbers:
<langsyntaxhighlight lang="maple">sample := proc( n )
local data;
data := Sample( Uniform(0,1), n );
Line 2,958:
return Statistics:-Histogram( data );
end proc:
sample( 1000 );</langsyntaxhighlight>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">Sample[n_]:= (Print[#//Length," numbers, Mean : ",#//Mean,", StandardDeviation : ",#//StandardDeviation ];
BarChart[BinCounts[#,{0,1,.1}], Axes->False, BarOrigin->Left])&[(RandomReal[1,#])&[ n ]]
Sample/@{100,1 000,10 000,1 000 000} </langsyntaxhighlight>
{{out}}
<pre>100 numbers, Mean : 0.478899, StandardDeviation : 0.322265
Line 2,972:
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight Matlablang="matlab"> % Initialize
N = 0; S=0; S2 = 0;
binlist = 0:.1:1;
Line 2,991:
m = S/N; % mean
sd = sqrt(S2/N-mean*mean); % standard deviation
bar(binlist,h)</langsyntaxhighlight>
 
=={{header|MiniScript}}==
A little Stats class is defined that can calculate mean and standard deviation for a stream of numbers (of arbitrary size, so yes, this would work for a trillion numbers just as well as for one).
<langsyntaxhighlight MiniScriptlang="miniscript">Stats = {}
Stats.count = 0
Stats.sum = 0
Line 3,033:
print "Mean: " + st.mean + " Standard Deviation: " + st.stddev
st.histogram
end for</langsyntaxhighlight>
{{out}}
<pre>Samples: 100
Line 3,074:
=={{header|Nim}}==
The standard module “stats” provides procedures to compute the statistical moments. It is possible to compute them either on a list of values or incrementally using an object <code>RunningStat</code>. In the following program, we use the first method for the 100 numbers samples and we draw the histogram. For the 1_000, 10_000, 100_000 and 1_000_000 samples, we use the second method which avoids to store the values (but don’t draw the histogram).
<langsyntaxhighlight lang="nim">import random, sequtils, stats, strutils, strformat
 
proc drawHistogram(ns: seq[float]) =
Line 3,105:
rs.push(n)
echo &"μ = {rs.mean:.12f} σ = {rs.standardDeviation:.12f}"
echo()</langsyntaxhighlight>
{{out}}
<pre>For 100 numbers:
Line 3,136:
=={{header|Oforth}}==
 
<langsyntaxhighlight Oforthlang="oforth">: main(n)
| l m std i nb |
 
Line 3,150:
i 0.1 + <<wjp(3, JUSTIFY_RIGHT, 2) " - " <<
StringBuffer new "*" <<n(nb) << cr
] ;</langsyntaxhighlight>
 
{{out}}
Line 3,224:
=={{header|PARI/GP}}==
{{works with|PARI/GP|2.4.3 and above}}
<langsyntaxhighlight lang="parigp">mean(v)={
vecsum(v)/#v
};
Line 3,244:
show(100);
show(1000);
show(10000);</langsyntaxhighlight>
 
For versions before 2.4.3, define
<langsyntaxhighlight lang="parigp">rreal()={
my(pr=32*ceil(default(realprecision)*log(10)/log(4294967296))); \\ Current precision
random(2^pr)*1.>>pr
};</langsyntaxhighlight>
and use <code>rreal()</code> in place of <code>random(1.)</code>.
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">my @histogram = (0) x 10;
my $sum = 0;
my $sum_squares = 0;
Line 3,277:
print "*" x (30 * $histogram[$i] * @histogram/$n); # 30 stars expected per row
print "\n";
}</langsyntaxhighlight>
 
Usage: <pre>perl rand_statistics.pl (number of values)</pre>
Line 3,344:
{{trans|CoffeeScript}}
To do a trillion samples, I would change the existing generate loop into an inner 100_000_000 loop that still uses the fast native types, with everything outside that changed to bigatom, and of course add an outer loop which sums into them.
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">function</span> <span style="color: #000000;">generate_statistics</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">n</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">hist</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">repeat</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0</span><span style="color: #0000FF;">,</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)</span>
Line 3,379:
<span style="color: #000000;">display_statistics</span><span style="color: #0000FF;">(</span><span style="color: #000000;">generate_statistics</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">power</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">n</span><span style="color: #0000FF;">+(</span><span style="color: #000000;">n</span><span style="color: #0000FF;">=</span><span style="color: #000000;">5</span><span style="color: #0000FF;">))))</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<!--</langsyntaxhighlight>-->
{{Out}}
<pre style="float:left; font-size: 10px">
Line 3,444:
=={{header|PicoLisp}}==
The following has no limit on the number of samples. The 'statistics' function accepts an executable body 'Prg', which it calls repeatedly to get the samples.
<syntaxhighlight lang="picolisp">
<lang PicoLisp>
(seed (time))
 
Line 3,473:
(rand 0 (dec 1.0)) )
(prinl) )
</syntaxhighlight>
</lang>
{{out}}
<pre>100 numbers
Line 3,518:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli"> stat: procedure options (main); /* 21 May 2014 */
 
stats: procedure (values, mean, standard_deviation);
Line 3,556:
end;
 
end stat;</langsyntaxhighlight>
{{out}}
<pre>
Line 3,579:
{{trans|Liberty BASIC}}
Changes were made from the Liberty BASIC version to normalize the histogram as well as implement a random float function.
<langsyntaxhighlight lang="purebasic">Procedure.f randomf()
#RNG_max_resolution = 2147483647
ProcedureReturn Random(#RNG_max_resolution) / #RNG_max_resolution
Line 3,634:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>100 data terms used.
Line 3,682:
=={{header|Python}}==
The second function, sd2 only needs to go once through the numbers and so can more efficiently handle large streams of numbers.
<langsyntaxhighlight lang="python">def sd1(numbers):
if numbers:
mean = sum(numbers) / len(numbers)
Line 3,720:
print(' Naive method: sd: %8.6f, mean: %8.6f' % sd1(n))
print(' Second method: sd: %8.6f, mean: %8.6f' % sd2(n))
histogram(n)</langsyntaxhighlight>
 
{{out}}
Line 3,764:
=={{header|R}}==
The challenge of processing a trillion numbers is generating them in the first place. As the errors below show, allocating 7.5 TB for such a vector is simply impractical. The workaround is to generate them, process individual data points and then discard them. The downside in this case is the time.
<syntaxhighlight lang="r">
<lang R>
#Generate the sets
a = runif(10,min=0,max=1)
Line 3,791:
cat("Mean of a trillion random values in the range [0,1] : ",mean(runif(10^12,min=0,max=1)))
cat("Standard Deviation of a trillion random values in the range [0,1] : ", sd(runif(10^12,min=0,max=1)))
</syntaxhighlight>
</lang>
Output
<pre>
Line 3,812:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require math (only-in srfi/27 random-real))
Line 3,834:
(task 1000)
(task 10000)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,883:
(formerly Perl 6)
{{Works with|rakudo|2018.03}}
<syntaxhighlight lang="raku" perl6line>for 100, 1_000, 10_000 -> $N {
say "size: $N";
my @data = rand xx $N;
Line 3,892:
for sort @data.classify: (10 * *).Int / 10;
say '';
}</langsyntaxhighlight>
{{out}}
<pre>size: 100
Line 3,938:
=={{header|REXX}}==
Twenty decimal digits are used for the calculations, but only half that (ten digits) are displayed in the output.
<langsyntaxhighlight lang="rexx">/*REXX program generates some random numbers, shows bin histogram, finds mean & stdDev. */
numeric digits 20 /*use twenty decimal digits precision, */
showDigs=digits()%2 /* ··· but only show ten decimal digits*/
Line 3,969:
numeric digits; parse value format(x,2,1,,0) 'E0' with g 'E' _ .; g=g*.5'e'_ % 2
do j=0 while h>9; m.j=h; h=h%2+1; end /*j*/
do k=j+5 to 0 by -1; numeric digits m.k; g=(g+x/g)*.5; end /*k*/; return g</langsyntaxhighlight>
{{out|output|text=&nbsp; when using the default input of: &nbsp; &nbsp; <tt> 100 </tt>}}
<pre>
Line 4,062:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
# Project : Statistics/Basic
 
Line 4,101:
next
see nl
</syntaxhighlight>
</lang>
Output:
<pre>
Line 4,172:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">def generate_statistics(n)
sum = sum2 = 0.0
hist = Array.new(10, 0)
Line 4,191:
end
 
[100, 1000, 10000].each {|n| generate_statistics n}</langsyntaxhighlight>
 
{{out}}
Line 4,239:
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">call sample 100
call sample 1000
call sample 10000
Line 4,280:
next b
print
end sub</langsyntaxhighlight>
<pre style="height: 40ex; overflow: scroll">
100 Samples used.
Line 4,327:
=={{header|Rust}}==
{{libheader|rand}}
<langsyntaxhighlight lang="rust">#![feature(iter_arith)]
extern crate rand;
 
Line 4,396:
print_histogram(40, &data);
}
}</langsyntaxhighlight>
{{out}}
<pre> Statistics for sample size 1000
Line 4,442:
 
=={{header|Scala}}==
<langsyntaxhighlight lang="scala">def mean(a:Array[Double])=a.sum / a.size
def stddev(a:Array[Double])={
val sum = a.fold(0.0)((a, b) => a + math.pow(b,2))
Line 4,462:
printHist(a)
println
}</langsyntaxhighlight>
{{out}}
<pre>100 numbers
Line 4,511:
=={{header|Sidef}}==
{{trans|Ruby}}
<langsyntaxhighlight lang="ruby">func generate_statistics(n) {
var(sum=0, sum2=0);
var hist = 10.of(0);
Line 4,536:
}
 
[100, 1000, 10000].each {|n| generate_statistics(n) }</langsyntaxhighlight>
{{out}}
<pre style="height: 40ex; overflow: scroll">
Line 4,586:
For a uniform distribution on [0,1], the mean is 1/2 and the variance is 1/12 (hence the standard deviation is 0.28867513). With a large sample, one can check the convergence to these values.
 
<langsyntaxhighlight lang="stata">. clear all
. set obs 100000
number of observations (_N) was 0, now 100,000
Line 4,595:
-------------+---------------------------------------------------------
x | 100,000 .4991874 .2885253 1.18e-06 .9999939
. hist x</langsyntaxhighlight>
 
=={{header|Tcl}}==
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
proc stats {size} {
set sum 0.0
Line 4,624:
stats 1000
puts ""
stats 10000</langsyntaxhighlight>
{{out}}
<pre>
Line 4,672:
 
=={{header|VBA}}==
<langsyntaxhighlight lang="vb">Option Base 1
Private Function mean(s() As Variant) As Double
mean = WorksheetFunction.Average(s)
Line 4,696:
Debug.Print
Next e
End Sub</langsyntaxhighlight>{{out}}
<pre>sample size 100 mean 0,472405961751938 standard deviation 0,260463885857138
0,00-0,10 XXXXXX
Line 4,735:
=={{header|Vlang}}==
{{trans|go}}
<langsyntaxhighlight lang="vlang">import rand
import math
 
Line 4,769:
}
println('')
}</langsyntaxhighlight>
 
{{out}}
Line 4,817:
</pre>
Or use standard math.stats module
<syntaxhighlight lang="text">import rand
import math.stats
 
Line 4,846:
}
println('')
}</langsyntaxhighlight>
{{out}}
Similar to above
Line 4,852:
=={{header|Wren}}==
{{libheader|Wren-math}}
<langsyntaxhighlight lang="ecmascript">import "random" for Random
import "/math" for Nums
 
Line 4,875:
sums[9] = 100 - Nums.sum(sums[0..8])
System.print(" 0.9 - 1.0: %("*" * sums[9])\n")
}</langsyntaxhighlight>
 
{{out}}
Line 4,927:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn mean(ns) { ns.sum(0.0)/ns.len() }
fcn stdDev(ns){
m:=mean(ns); (ns.reduce('wrap(p,n){ x:=(n-m); p+x*x },0.0)/ns.len()).sqrt()
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">reg ns;
foreach n in (T(100,1000,10000)){
ns=(0).pump(n,List,(0.0).random.fp(1.0));
Line 4,939:
n:=ns.filter('wrap(x){ r<=x<(r+0.1) }).len();
println("%.2f..%.2f:%4d%s".fmt(r,r+0.1,n,"*"*(n/20)));
}</langsyntaxhighlight>
(0.0).random(1.0) generates a [uniform] random number between 0 (inclusive) and 1 (exclusive).
{{out}}
Line 4,958:
</pre>
For the extra credit, pretend we have a device that spews random numbers in the range [0..1) forever. We connect this device to a measuring device that calculates mean and std deviation, printing results on a regular basis.
<langsyntaxhighlight lang="zkl">var pipe=Thread.Pipe(); // used to connect the two threads
fcn{ while(1){ pipe.write((0.0).random(1.0)) } }.launch(); // generator
fcn{ // consumer/calculator
Line 4,970:
}.launch();
 
Atomic.sleep(60*60); // wait because exiting the VM kills the threads</langsyntaxhighlight>
{{out}}
<pre>
10,333

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.