Averages/Arithmetic mean: Difference between revisions

m
(1-based index)
(19 intermediate revisions by 11 users not shown)
Line 329:
=={{header|APL}}==
{{works with|APL2}}
<syntaxhighlight lang="apl"> X←3 1 4 1 5 9
X←3 1 4 1 5 9
(+/X)÷⍴X
3.833333333</syntaxhighlight>
</syntaxhighlight>
 
{{works with|Dyalog APL}}
A proper function definition:
<syntaxhighlight lang="apl">
Avg←{(+⌿⍵)÷≢⍵}
Avg 1 2 3 4 5 6
3.5
</syntaxhighlight>
 
Using [[tacit programming]]:
<syntaxhighlight lang="apl">
Avg← +⌿÷≢
Avg 1 2 3 4 5 6
3.5
</syntaxhighlight>
'''N.B.:''' the symbol for [https://aplwiki.com/wiki/Tally Tally (≢)] doesn't display correctly on Chrome-based browsers at the moment.
 
=={{header|AppleScript}}==
Line 857 ⟶ 875:
(/ (loop for i in list sum i)
(length list))))</syntaxhighlight>
 
=={{header|Craft Basic}}==
<syntaxhighlight lang="basic">dim a[3, 1, 4, 1, 5, 9]
 
arraysize s, a
 
for i = 0 to s - 1
 
let t = t + a[i]
 
next i
 
print t / s</syntaxhighlight>
{{out| Output}}<pre>3.83</pre>
 
=={{header|Crystal}}==
Line 1,013 ⟶ 1,045:
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">func mean . f[] r .
proc mean . f[] r .
for i = 1 to len f[]
for si += 1 to len f[i]
s += f[i]
.
.
r = s / len f[]
r = s / len f[]
.
f[] = [ 1 2 3 4 5 6 7 8 ]
call mean f[] r
print r
</syntaxhighlight>
Line 1,059 ⟶ 1,092:
AveVal(SetVals) //returns 30.0 ;
</syntaxhighlight>
 
=={{header|EDSAC order code}}==
Extends the RC task by finding the arithmetic mean for each of several data sets. Each data set is preceded by the number of data. A count of 0 is not an error but signals that there are no more data sets.
 
The program needs to avoid the possibility of arithmetic overflow, as pointed out in the F# solution. The moving average used there is not well-suited to EDSAC, on which division had to be done by calling a subroutine. After reading the number of data N, and leaving the trivial case N = 1 for separate treatment, the program first calculates 1/N, then multiplies each value by 1/N before adding it into the result.
<syntaxhighlight lang="edsac">
[Averages/Arithmetic mean - Rosetta Code]
 
[EDSAC program (Initial Orders 2) to find and print the average of
a sequence of 35-bit fractional values.
Values are read from tape, preceded by an integer count.]
 
[Library subroutine M3, runs at load time and is then overwritten.
Prints header; here, last character sets teleprinter to figures.]
PF GK IF AF RD LF UF OF E@ A6F G@ E8F EZ PF
*!!!!!COUNT!!!!!!AVERAGE@&#.. [PZ]
 
[Main routine: must be at even address]
T214K GK
[0] PF PF [average value]
[2] PF PF [reciprocal of data count]
[4] PF [data count]
[5] PD [17-bit constant 1; also serves as '0' for printing]
[6] @F [carriage return]
[7] &F [line feed]
[8] !F [space]
[9] MF [dot (in figures mode)]
[10] K4096F [teleprinter null]
[Entry and outer loop]
[11] A11@
G56F [call library subroutine R4, sets 0D := data count N]
SD E64@ [exit if N = 0]
T4F [clear acc]
AF T4@ [load and save N (assumed < 2^16)]
[18] A18@ G156F [print N (clears acc)]
TD [clear whole of 0D, including sandwich bit]
T4D [same for 4D]
A4@ S2F [acc := N - 2]
G66@ [jump to special action if N = 1]
A2F [restore N after test]
T5F [store N in 4D high word]
A5@ T1F [store 1 in 0D high word]
[29] A29@ G120F [call library subroutine D6, sets 0D := 0D/4D]
AD T2#@ [load and save 1/N]
T#@ [clear average]
S4@ [load -N]
[Inner loop]
[35] T4@ [update negative loop counter]
[36] A36@ G78F [read next datum to 0D (clears acc)]
H2#@ [mult reg := 1/N]
VD [acc := datum/N]
A#@ T#@ [add into average]
A4@ A5@ [increment negative loop counter]
G35@ [loop until counter = 0]
[45] O8@ O8@ [print 2 spaces]
[Print the average value.
NB: Library subroutine P1 requires non-negative input and prints only the
digits after the decimal point. Formatting has to be done by the caller.]
[47] A#@ [load average (order also serves as minus sign)]
G52@ [jump if average < 0]
TD [pass average to subroutine P1]
O65@ [print plus sign (or could be space)]
E56@ [join common code]
[52] TD [average < 0; clear acc]
S#@ TD [pass abs(average) to subroutine P1]
O47@ [print minus sign]
[56] O5@ O9@ [common code: print '0.']
[58] A58@ G192F [call P1 to print abs(average)]
P8F [8 decimal places]
O6@ O7@ [print CR, LF]
E11@ [loop back always (because acc = 0)]
[Jump to here if data count = 0, means end of data]
[64] O10@ [print null to flush teleprinter buffer]
[65] ZF [halt the machine (order also serves as plus sign)]
[Jump to here if data count = 1]
[66] TF [clear acc]
[67] A67@ G78F [read datum to 0D]
AD T#@ [average := datum]
E45@ [jump to print the average]
 
[The following puts the entry address into location 50,
so that it can be accessed via the X parameter (see end of program).
This is done in case the data is input from a separate tape.]
T50K P11@ T11Z
 
[Library subroutine R4.
Input of one signed integer, returned in 0D.]
T56K
GKA3FT21@T4DH6@E11@P5DJFT6FVDL4FA4DTDI4FA4FS5@G7@S5@G20@SDTDT6FEF
 
[Library subroutine R3.
Input of one long signed decimal fraction, returned in 0D.]
T78K
GKT45KP26@TZA3FTHTDT4DA6HT9@H1HS4HT6FIFAFS4HE7HT7FV4DL8FADT4DA6FA5HG8@
H2#HN4DLDYFTDT28#ZPFT27ZTFP610D@524DP5DPDIFS4HG37@S4DT4DT7FA1HT9@E18@
 
[Library subroutine D6 - Division, accurate, fast.
36 locations, workspace 6D and 8D.
0D := 0D/4D, where 4D <> 0, -1.]
T120K
GKA3FT34@S4DE13@T4DSDTDE2@T4DADLDTDA4DLDE8@RDU4DLDA35@
T6DE25@U8DN8DA6DT6DH6DS6DN4DA4DYFG21@SDVDTDEFW1526D
 
[Library subroutine P7: print strictly positive integer in 0D.]
T156K
GKA3FT26@H28#@NDYFLDT4DS27@TFH8@S8@T1FV4DAFG31@SFLDUFOFFFSF
L4FT4DA1FA27@G11@T28#ZPFT27ZP1024FP610D@524D!FO30@SFL8FE22@
 
[Library subroutine P1: print non-negative fraction in 0D, without '0.']
T192K
GKA18@U17@S20@T5@H19@PFT5@VDUFOFFFSFL4FTDA5@A2FG6@EFU3FJFM1F
 
[==========================================================================
On the original EDSAC, the following (without the whitespace and comments)
might have been input on a separate tape.]
 
E25K TX GK
EZ [define entry point]
PF [acc = 0 on entry]
 
[Counts and data values to be read by library subroutines R3 and R4 respectively.
Note (1) Sign comes *after* value (2) In the data, leading '0.' is omitted.]
7+ 1-2-3-4-5+2-3-
1+ 987654321+
9+ 01+04+09+16+25+36+49+64+81+
9+ 01-04+09-16+25-36+49-64+81-
[Daily minimum temperature (unit = 10 deg. C), Cambridge, UK, January 2000]
31+ 34+14+49+00+04+48+05+48+23-35-07-75+19+03+
26+27+17-06-52+22-17+18+15+03-33-11-04-01-44+89+95+
0+
</syntaxhighlight>
{{out}}
<pre>
COUNT AVERAGE
7 -0.14285714
1 +0.98765432
9 +0.31666666
9 -0.05000000
31 +0.16774193
</pre>
 
=={{header|Elena}}==
ELENA 56.0x:
<syntaxhighlight lang="elena">import extensions;
 
Line 1,075 ⟶ 1,248:
while (enumerator.next())
{
sum += *enumerator.get();
count += 1;
};
Line 1,109 ⟶ 1,282:
<syntaxhighlight lang="lisp">(let ((x '(1 2 3 4)))
(calc-eval "vmean($1)" nil (append '(vec) x)))</syntaxhighlight>
 
=={{header|EMal}}==
<syntaxhighlight lang="emal">
fun mean = real by some real values
real sum
int count
for each real value in values
sum += value
++count
end
return when(count == 0, 0.0, sum / count)
end
writeLine(mean())
writeLine(mean(3,1,4,1,5,9))
</syntaxhighlight>
{{out}}
<pre>
0.0
3.8333333333333333333333333333
</pre>
 
=={{header|Erlang}}==
Line 1,716 ⟶ 1,909:
{{Out}}
<syntaxhighlight lang="javascript">5</syntaxhighlight>
 
=={{header|Joy}}==
<syntaxhighlight lang="joy">DEFINE avg == dup 0. [+] fold swap size 1 max /.</syntaxhighlight>
 
=={{header|jq}}==
Line 1,785 ⟶ 1,981:
We could use fold() to write a function that takes an array and calculates the mean.
 
<syntaxhighlight lang="langur">val .mean = fn(.x) { fold(fn{+}, .x) / len(.x) }
{{works with|langur|0.6.6}}
<syntaxhighlight lang="langur">val .mean = f(.x) fold(f{+}, .x) / len(.x)
 
writeln " custom: ", .mean([7, 3, 12])
Line 2,201 ⟶ 2,396:
=={{header|min}}==
Returns <code>nan</code> for an empty quotation.
{{works with|min|0.1937.30}}
<syntaxhighlight lang="min">(((02 (+)3 reduce5) (sizeavg puts!</)) cleave) :meansyntaxhighlight>
(2 3 5) mean print</syntaxhighlight>
{{out}}
<pre>3.333333333333333</pre>
<pre>
3.333333333333334
</pre>
 
=={{header|MiniScript}}==
Line 3,199 ⟶ 3,391:
</syntaxhighlight>
 
=={{header|RPL/2}}==
This is based on the dc version above.
{{works with|HP|48G}}
≪ DUP 'N' STO →LIST ΣLIST N / 'N' PURGE ≫ '<span style="color:blue">AMEAN</span>' STO
or,by using the stack instead of a temporary variable:
≪ →LIST ΣLIST LASTARG SIZE / ≫ '<span style="color:blue">AMEAN</span>' STO
 
CLEAR 1 2 3 5 7 DEPTH <span style="color:blue">AMEAN</span>
This is a simple rewrite of the dc version above. This works on an HP 48. "->" is a single right arrow character on the 48. Feel free to alter this code as necessary to work on RPL/2.
 
===Hard-working approach===
<syntaxhighlight lang="rpl/2">1 2 3 5 7
Works for all RPL versions.
AMEAN
≪ DUP SIZE SWAP OVER
<< DEPTH DUP 'N' STO ->LIST ΣLIST N / >>
0 1 ROT '''FOR''' j
3.6</syntaxhighlight>
OVER j GET + '''NEXT'''
ROT / SWAP DROP
===Hard-working approach with local variables===
No significant impact on program size or speed, but much more readable
≪ DUP SIZE → vector n
≪ 0 1 n '''FOR''' j
vector j GET + '''NEXT'''
n /
≫ ≫
===Straightforward approach===
The dot product of any vector with [1 1 ... 1] gives the sum of its elements.
≪ SIZE LAST DUP 1 CON DOT SWAP / ≫
''''AMEAN'''' STO
 
===Using built-in statistics features===
Most of the code is dedicated to store the input array according to built-in statistics requirements, which requires a matrix with one line per record. Main benefit of this approach is that you can then easily calculate standard deviation and variance by calling resp. <code>SDEV</code> and <code>VAR</code> functions.
≪ { 1 } OVER SIZE + RDM TRN '∑DAT' STO MEAN ≫ ''''AMEAN'''' STO
 
[ 1 5 0 -4 6 ] '''AMEAN'''
{{out}}
<pre>
1: 1.6
</pre>
 
=={{header|Ruby}}==
Line 3,356 ⟶ 3,577:
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">func avg(Array list) {
list.len > 0 || return 0;
list.sum / list.len;
}
 
say avg([Math.infInf, Math.infInf]);
say avg([3,1,4,1,5,9]);
say avg([1e+20, 3, 1, 4, 1, 5, 9, -1e+20]);
say avg([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, 0.11]);
say avg([10, 20, 30, 40, 50, -100, 4.7, -1100]);</syntaxhighlight>
{{out}}
<pre>inf
Inf
3.833333333333333333333333333333333333333
3.83333333333333333333333333333333333333333333333
2.875
3.674
-130.6625</pre>
</pre>
 
=={{header|Slate}}==
Line 3,893 ⟶ 4,116:
 
=={{header|Wren}}==
<syntaxhighlight lang="ecmascriptwren">class Arithmetic {
static mean(arr) {
if (arr.count == 0) Fiber.abort("Length must be greater than zero")
885

edits