Add all the A tasks

This commit is contained in:
Ingy döt Net 2013-04-10 14:58:50 -07:00
parent 2dd7375f96
commit 051504d65b
1608 changed files with 18584 additions and 0 deletions

View file

@ -0,0 +1,3 @@
Write a program to find the [[wp:arithmetic mean|mean]] (arithmetic average) of a numeric vector. In case of a zero-length input, since the mean of an empty set of numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
See also: [[Median]], [[Mode]]

View file

@ -0,0 +1,2 @@
---
note: Probability and statistics

View file

@ -0,0 +1,40 @@
ArithmeticMean: PHA
TYA
PHA ;push accumulator and Y register onto stack
LDA #0
STA Temp
STA Temp+1 ;temporary 16-bit storage for total
LDY NumberInts
BEQ Done ;if NumberInts = 0 then return an average of zero
DEY ;start with NumberInts-1
AddLoop: LDA (ArrayPtr),Y
CLC
ADC Temp
STA Temp
LDA Temp+1
ADC #0
STA Temp+1
DEY
CPY #255
BNE AddLoop
LDY #-1
DivideLoop: LDA Temp
SEC
SBC NumberInts
STA Temp
LDA Temp+1
SBC #0
STA Temp+1
INY
BCS DivideLoop
Done: STY ArithMean ;store result here
PLA ;restore accumulator and Y register from stack
TAY
PLA
RTS ;return from routine

View file

@ -0,0 +1,13 @@
(defun mean-r (xs)
(if (endp xs)
(mv 0 0)
(mv-let (m j)
(mean-r (rest xs))
(mv (+ (first xs) m) (+ j 1)))))
(defun mean (xs)
(if (endp xs)
0
(mv-let (n d)
(mean-r xs)
(/ n d))))

View file

@ -0,0 +1,13 @@
PROC mean = (REF[]REAL p)REAL:
# Calculates the mean of qty REALs beginning at p. #
IF LWB p > UPB p THEN 0.0
ELSE
REAL total := 0.0;
FOR i FROM LWB p TO UPB p DO total +:= p[i] OD;
total / (UPB p - LWB p + 1)
FI;
main:(
[6]REAL test := (1.0, 2.0, 5.0, -5.0, 9.5, 3.14159);
print((mean(test),new line))
)

View file

@ -0,0 +1,3 @@
X3 1 4 1 5 9
(+/X)÷X
3.833333333

View file

@ -0,0 +1,27 @@
# work around a gawk bug in the length extended use:
# so this is a more non-gawk compliant way to get
# how many elements are in an array
function elength(v)
{
l=0
for(el in v) l++
return l
}
function mean(v)
{
if (elength(v) < 1) { return 0 }
sum = 0
for(i=0; i < elength(v); i++) {
sum += v[i]
}
return sum/elength(v)
}
BEGIN {
# fill a vector with random numbers
for(i=0; i < 10; i++) {
vett[i] = rand()*10
}
print mean(vett)
}

View file

@ -0,0 +1,7 @@
function mean(vector:Vector.<Number>):Number
{
var sum:Number = 0;
for(var i:uint = 0; i < vector.length; i++)
sum += vector[i];
return vector.length == 0 ? 0 : sum / vector.length;
}

View file

@ -0,0 +1,25 @@
with Ada.Float_Text_Io; use Ada.Float_Text_Io;
with Ada.Text_IO; use Ada.Text_IO;
procedure Mean_Main is
type Vector is array(Positive range <>) of Float;
function Mean(Item : Vector) return Float is
Sum : Float := 0.0;
Result : Float := 0.0;
begin
for I in Item'range loop
Sum := Sum + Item(I);
end loop;
if Item'Length > 0 then
Result := Sum / Float(Item'Length);
end if;
return Result;
end Mean;
A : Vector := (3.0, 1.0, 4.0, 1.0, 5.0, 9.0);
begin
Put(Item => Mean(A), Fore => 1, Exp => 0);
New_Line;
-- test for zero length vector
Put(Item => Mean(A(1..0)), Fore => 1, Exp => 0);
New_Line;
end Mean_Main;

View file

@ -0,0 +1,14 @@
PROC mean(l:PTR TO LONG)
DEF m, i, ll
ll := ListLen(l)
IF ll = 0 THEN RETURN 0.0
m := 0.0
FOR i := 0 TO ll-1 DO m := !m + l[i]
m := !m / (ll!)
ENDPROC m
PROC main()
DEF s[20] : STRING
WriteF('mean \s\n',
RealF(s,mean([1.0, 2.0, 3.0, 4.0, 5.0]), 2))
ENDPROC

View file

@ -0,0 +1,7 @@
i = 10
Loop, % i {
Random, v, -3.141592, 3.141592
list .= v "`n"
sum += v
}
MsgBox, % i ? list "`nmean: " sum/i:0

View file

@ -0,0 +1,12 @@
mean = 0
sum = 0;
FOR i = LBOUND(nums) TO UBOUND(nums)
sum = sum + nums(i);
NEXT i
size = UBOUND(nums) - LBOUND(nums) + 1
PRINT "The mean is: ";
IF size <> 0 THEN
PRINT (sum / size)
ELSE
PRINT 0
END IF

View file

@ -0,0 +1,3 @@
0001>p&: #v_$::01g/.@
^10+1g10+<
Enter 0 (zero) to finish.

View file

@ -0,0 +1,24 @@
#include <stdio.h>
double mean(double *v, int len)
{
double sum = 0;
int i;
for (i = 0; i < len; i++)
sum += v[i];
return sum / len;
}
int main(void)
{
double v[] = {1, 2, 2.718, 3, 3.142};
int i, len;
for (len = 5; len >= 0; len--) {
printf("mean[");
for (i = 0; i < len; i++)
printf(i ? ", %g" : "%g", v[i]);
printf("] = %g\n", mean(v, len));
}
return 0;
}

View file

@ -0,0 +1,6 @@
(defn mean [sq]
(let [length (count sq)]
(if (zero? length)
0
(/ (reduce + sq) length)))
)

View file

@ -0,0 +1,7 @@
mean = (array) ->
return 0 if array.length is 0
sum = array.reduce (s,i,0) -> s += i
sum / array.length
alert mean [1]

View file

@ -0,0 +1,2 @@
mean([]) -> 0;
mean(L) -> lists:sum(L)/length(L).

View file

@ -0,0 +1,10 @@
: fmean ( addr n -- f )
0e
dup 0= if 2drop exit then
tuck floats bounds do
i f@ f+
1 floats +loop
0 d>f f/ ;
create test 3e f, 1e f, 4e f, 1e f, 5e f, 9e f,
test 6 fmean f. \ 3.83333333333333

View file

@ -0,0 +1,20 @@
real, target, dimension(100) :: a = (/ (i, i=1, 100) /)
real, dimension(5,20) :: b = reshape( a, (/ 5,20 /) )
real, pointer, dimension(:) :: p => a(2:1) ! pointer to zero-length array
real :: mean, zmean, bmean
real, dimension(20) :: colmeans
real, dimension(5) :: rowmeans
mean = sum(a)/size(a) ! SUM of A's elements divided by SIZE of A
mean = sum(a)/max(size(a),1) ! Same result, but safer code
! MAX of SIZE and 1 prevents divide by zero if SIZE == 0 (zero-length array)
zmean = sum(p)/max(size(p),1) ! Here the safety check pays off. Since P is a zero-length array,
! expression becomes "0 / MAX( 0, 1 ) -> 0 / 1 -> 0", rather than "0 / 0 -> NaN"
bmean = sum(b)/max(size(b),1) ! multidimensional SUM over multidimensional SIZE
rowmeans = sum(b,1)/max(size(b,2),1) ! SUM elements in each row (dimension 1)
! dividing by the length of the row, which is the number of columns (SIZE of dimension 2)
colmeans = sum(b,2)/max(size(b,1),1) ! SUM elements in each column (dimension 2)
! dividing by the length of the column, which is the number of rows (SIZE of dimension 1)

View file

@ -0,0 +1,65 @@
package main
import (
"fmt"
"math"
)
func mean(v []float64) (m float64, ok bool) {
if len(v) == 0 {
return
}
// an algorithm that attempts to retain accuracy
// with widely different values.
var parts []float64
for _, x := range v {
var i int
for _, p := range parts {
sum := p + x
var err float64
switch ax, ap := math.Abs(x), math.Abs(p); {
case ax < ap:
err = x - (sum - p)
case ap < ax:
err = p - (sum - x)
}
if err != 0 {
parts[i] = err
i++
}
x = sum
}
parts = append(parts[:i], x)
}
var sum float64
for _, x := range parts {
sum += x
}
return sum / float64(len(v)), true
}
func main() {
for _, v := range [][]float64{
[]float64{}, // mean returns ok = false
[]float64{math.Inf(1), math.Inf(1)}, // answer is +Inf
// answer is NaN, and mean returns ok = true, indicating NaN
// is the correct result
[]float64{math.Inf(1), math.Inf(-1)},
[]float64{3, 1, 4, 1, 5, 9},
// large magnitude numbers cancel. answer is mean of small numbers.
[]float64{1e20, 3, 1, 4, 1, 5, 9, -1e20},
[]float64{10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0, .11},
[]float64{10, 20, 30, 40, 50, -100, 4.7, -11e2},
} {
fmt.Println("Vector:", v)
if m, ok := mean(v); ok {
fmt.Printf("Mean of %d numbers is %g\n\n", len(v), m)
} else {
fmt.Println("Mean undefined\n")
}
}
}

View file

@ -0,0 +1,3 @@
mean :: (Fractional a) => [a] -> a
mean [] = 0
mean xs = sum xs / Data.List.genericLength xs

View file

@ -0,0 +1,2 @@
meanReals :: (Real a, Fractional b) => [a] -> b
meanReals = mean . map realToFrac

View file

@ -0,0 +1,5 @@
{-# LANGUAGE BangPatterns #-}
import Data.List (foldl')
mean :: (Real n, Fractional m) => [n] -> m
mean xs = let (s,l) = foldl' f (0, 0) xs in realToFrac s / l
where f (!s,!l) x = (s+x,l+1)

View file

@ -0,0 +1,7 @@
...
double sum = 0;
for(double i : nums){
sum += i;
}
System.out.println("The mean is: " + ((nums.length != 0) ? (sum / nums.length) : 0));
...

View file

@ -0,0 +1,11 @@
function mean(array)
{
var sum = 0, i;
for (i = 0; i < array.length; i++)
{
sum += array[i];
}
return array.length ? sum / array.length : 0;
}
alert( mean( [1,2,3,4,5] ) ); // 3

View file

@ -0,0 +1,4 @@
function mean(a)
{
return a.length ? Functional.reduce('+', 0, a) / a.length : 0;
}

View file

@ -0,0 +1,8 @@
function mean (numlist)
if type(numlist) ~= 'table' then return numlist end
num = 0
table.foreach(numlist,function(i,v) num=num+v end)
return num / #numlist
end
print (mean({3,1,4,1,5,9}))

View file

@ -0,0 +1,5 @@
$nums = array(3, 1, 4, 1, 5, 9);
if ($nums)
echo array_sum($nums) / count($nums), "\n";
else
echo "0\n";

View file

@ -0,0 +1,8 @@
sub avg {
@_ or return 0;
my $sum = 0;
$sum += $_ foreach @_;
return $sum/@_;
}
print avg(qw(3 1 4 1 5 9)), "\n";

View file

@ -0,0 +1,5 @@
use Data::Average;
my $d = Data::Average->new;
$d->add($_) foreach qw(3 1 4 1 5 9);
print $d->avg, "\n";

View file

@ -0,0 +1,4 @@
(de mean (Lst)
(if (atom Lst)
0
(/ (apply + Lst) (length Lst)) ) )

View file

@ -0,0 +1,5 @@
from math import fsum
def average(x):
return fsum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))

View file

@ -0,0 +1,2 @@
2.3
2.3

View file

@ -0,0 +1,4 @@
def average(x):
return sum(x)/float(len(x)) if x else 0
print (average([0,0,3,1,4,1,5,9,0,0]))
print (average([1e20,-1e-20,3,1,4,1,5,9,-1e20,1e-20]))

View file

@ -0,0 +1,2 @@
2.3
1e-21

View file

@ -0,0 +1,6 @@
def avg(data):
if len(data)==0:
return 0
else:
return sum(data)/float(len(data))
print avg([0,0,3,1,4,1,5,9,0,0])

View file

@ -0,0 +1 @@
2.3

View file

@ -0,0 +1,4 @@
omean <- function(v) {
m <- mean(v)
ifelse(is.na(m), 0, m)
}

View file

@ -0,0 +1,20 @@
/*REXX pgm finds the averages/arithmetic mean of several lists (vectors)*/
@.1 = 10 9 8 7 6 5 4 3 2 1
@.2 = 10 9 8 7 6 5 4 3 2 1 0 0 0 0 .11
@.3 = '10 20 30 40 50 -100 4.7 -11e2'
@.4 = '1 2 3 4 five 6 7 8 9 10.1. ±2'
@.5 = 'World War I & World War II'
@.6 = ''
do j=1 for 6
say 'numbers = ' @.j; say 'average = ' avg(@.j); say
end /*t*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────AVG subroutine──────────────────────*/
avg: procedure; parse arg x; w=words(x); s=0; $=left('',20)
if w==0 then return 'N/A: [null vector.]'
do k=1 for w; _=word(x,k)
if datatype(_,'N') then do; s=s+_; iterate; end
say $ '***error!*** non-numeric: ' _; w=w-1 /*adjust W*/
end /*k*/
if w==0 then return 'N/A: [no numeric values.]'
return s/max(1,w)

View file

@ -0,0 +1,6 @@
#lang racket
(require math)
(mean (in-range 0 1000)) ; -> 499 1/2
(mean '(2 2 4 4)) ; -> 3
(mean #(3 4 5 8)) ; -> 5

View file

@ -0,0 +1,2 @@
nums = [3, 1, 4, 1, 5, 9]
nums.empty? ? 0 : nums.inject(:+) / Float(nums.size)

View file

@ -0,0 +1,14 @@
class VECOPS is
mean(v:VEC):FLT is
m ::= 0.0;
loop m := m + v.aelt!; end;
return m / v.dim.flt;
end;
end;
class MAIN is
main is
v ::= #VEC(|1.0, 5.0, 7.0|);
#OUT + VECOPS::mean(v) + "\n";
end;
end;

View file

@ -0,0 +1 @@
def mean(s: Seq[Int]) = s.foldLeft(0)(_+_) / s.size

View file

@ -0,0 +1,4 @@
def mean[T](s: Seq[T])(implicit n: Integral[T]) = {
import n._
s.foldLeft(zero)(_+_) / fromInt(s.size)
}

View file

@ -0,0 +1 @@
def mean[T](s: Seq[T])(implicit n: Fractional[T]) = n.div(s.sum, n.fromInt(s.size))

View file

@ -0,0 +1,4 @@
(define (mean l)
(if (null? l)
0
(/ (apply + l) (length l))))

View file

@ -0,0 +1,8 @@
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
(numbers isEmpty
ifTrue:[0]
ifFalse: [
(numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size ]
) displayNl.

View file

@ -0,0 +1,4 @@
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
( numbers inject: 0 into: [:sumSoFar :eachElement | sumSoFar + eachElement]) / numbers size] ) displayNl.

View file

@ -0,0 +1,4 @@
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
(numbers sum / numbers size) displayNl.

View file

@ -0,0 +1,4 @@
| numbers |
numbers := #(1 2 3 4 5 6 7 8).
numbers average displayNl.

View file

@ -0,0 +1,6 @@
package require Tcl 8.5
proc mean args {
if {[set num [llength $args]] == 0} {return 0}
expr {[tcl::mathop::+ {*}$args] / double($num)}
}
mean 3 1 4 1 5 9 ;# ==> 3.8333333333333335