함수 average()

1 개요[ | ]

AVERAGE()
avg
mean()
array_mean()
array_average()

2 C[ | ]

#include<stdio.h>

float intArray_mean(int arr[], int len) {
    float sum = 0;
    for(int i=0; i<len; i++) sum += arr[i];
    return sum / len;
}

void main() {
   int nums[] = {1,2,3,4};
   int len = sizeof(nums)/sizeof(nums[0]);
   printf("mean = %f", intArray_mean(nums,len));
   // mean = 2.500000
}

3 Excel[ | ]

=AVERAGE(1,2,3,4,5)
// 3

4 Java[ | ]

int[] nums = {1,2,7};
double avg = Arrays.stream(nums).average().getAsDouble(); // 3.3333333333333335
import java.util.Arrays;
public class Main {
    public static void main(String args[]) {
        int[] nums = {1,2,7};
        double avg = Arrays.stream(nums).average().getAsDouble();
        System.out.println(avg); // 3.3333333333333335
    }
}

5 PHP[ | ]

$nums = [1, 2, 3, 4, 5];
var_dump( array_sum($nums)/count($nums) ); # int(3)
$nums = [1, 2, 3, 4];
var_dump( array_sum($nums)/count($nums) ); # float(2.5)

6 Python[ | ]

Python 3
nums = [1, 2, 3, 4]
print( sum(nums)/len(nums) ) # 2.5
nums = [1, 2, 3, 4, 5]
print( sum(nums)/len(nums) ) # 3.0
Python 2
nums = [1, 2, 3, 4]
print( sum(nums)/len(nums) )
# 2
nums = [1, 2, 3, 4, 5]
print( sum(nums)/len(nums) )
# 3

nums = [1, 2, 3, 4]
print( 1.0*sum(nums)/len(nums) )
# 2.5
nums = [1, 2, 3, 4, 5]
print( 1.0*sum(nums)/len(nums) )
# 3.0
NumPy
import numpy as np
a = np.array([1,2,3,4])
print( a.mean() ) # 2.5

7 Perl[ | ]

모듈 사용
use Math::NumberCruncher;
my @array = (1, 2, 3, 4, 5);
print Math::NumberCruncher::Mean(\@array);
모듈 미사용
sub average {
	my @array = @_;
	my $sum;
	foreach (@array) { $sum += $_; }
	return $sum/@array;
}
my @dataArray = (1, 2, 3, 4, 5);
print average(@dataArray);

8 R[ | ]

x <- c(1,2,3,4,5)
print( mean(x) ) # 3

9 같이 보기[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}