Avg
avg calculates the average of the numbers in an array.
Overview
Use avg to find the average value in a collection of numbers.
temperatures | [68, 72, 75, 69] average | avg(temperatures) :say(average) /// 71
temperatures | [68, 72, 75, 69] average | avg(temperatures) :say(average) /// 71
Goblin adds the values together and divides the total by the number of values.
Number Types
avg accepts an array containing numeric values:
avg([8, 10, 12]) /// 10 avg([1.5, 2.5, 5.0]) /// 3
avg([8, 10, 12]) /// 10 avg([1.5, 2.5, 5.0]) /// 3
Integers, floats, percentages, and big numbers are numeric values.
For an array of integers, floats, or percentages, avg returns a float.
If the array contains a big number, avg uses big-number arithmetic and returns a big number.
Empty Arrays
The average of an empty array is 0.0:
avg([]) /// 0.0
avg([]) /// 0.0
This allows an empty collection to be averaged without raising an error.
Mixed Numbers
Integers, floats, and percentages may be used together:
measurements | [10, 12.5, 15] avg(measurements) /// 12.5
measurements | [10, 12.5, 15] avg(measurements) /// 12.5
Big-number calculations have stricter conversion rules. In the current interpreter, an array containing a big number cannot also contain an integer. Convert the integer to a big number first:
values | [big(10), big(20), big(30)] avg(values)
values | [big(10), big(20), big(30)] avg(values)
Signature
avg(numbers)
avg(numbers)
| Argument | Type | Description |
|---|---|---|
numbers |
array | The numeric values to average. |
avg returns a float for ordinary numeric arrays and a big number when big-number arithmetic is used.
Errors
avg requires exactly one argument:
avg([10, 20], [30, 40]) /// error: R0301 wrong-arity
avg([10, 20], [30, 40]) /// error: R0301 wrong-arity
The argument must be an array:
avg(10) /// error: R0402 array-expected
avg(10) /// error: R0402 array-expected
Every value in the array must be a compatible number:
avg([10, "twelve", 14]) /// error: R0200 numeric-expected
avg([10, "twelve", 14]) /// error: R0200 numeric-expected
A non-finite float cannot be converted for a big-number calculation:
/// error: T0320 non-finite-float
/// error: T0320 non-finite-float