XPath/XQuery avg function

Summary

Returns the average of the values in the input sequence $arg, that is, the sum of the values divided by the number of values.

Signature

fn:avg(
$arg as xs:anyAtomicType*
) as xs:anyAtomicType?

Properties

This function is deterministic, context-independent, and focus-independent.

Rules

If $arg is the empty sequence, the empty sequence is returned.

If $arg contains values of type xs:untypedAtomic they are cast to xs:double.

Duration values must either all be xs:yearMonthDuration values or must all be xs:dayTimeDuration values. For numeric values, the numeric promotion rules defined in are used to promote all values to a single common type. After these operations, $arg must satisfy the following condition:

There must be a type T such that:

  1. every item in $arg is an instance of T.
  2. T is one of xs:double, xs:float, xs:decimal, xs:yearMonthDuration, or xs:dayTimeDuration.

The function returns the average of the values as sum($arg) div count($arg); but the implementation may use an otherwise equivalent algorithm that avoids arithmetic overflow.

Examples

let $d1 := xs:yearMonthDuration("P20Y")

let $d2 := xs:yearMonthDuration("P10M")

let $seq3 := (3, 4, 5)

The expression fn:avg($seq3) returns 4.0.

The expression fn:avg(($d1, $d2)) returns xs:yearMonthDuration("P10Y5M").

fn:avg(($d1, $seq3)) raises a type error .

The expression fn:avg(()) returns ().

The expression fn:avg((xs:float('INF'), xs:float('-INF'))) returns xs:float('NaN').

The expression fn:avg(($seq3, xs:float('NaN'))) returns xs:float('NaN').

Error Conditions

A type error is raised if the input sequence contains items of incompatible types, as described above.