Skip to main content

Mojo function

variance

variance(src: NDBuffer[dtype, 1, origin], mean_value: Scalar[dtype], correction: Int = 1) -> Scalar[dtype]

Given a mean, computes the variance of elements in a buffer.

The mean value is used to avoid a second pass over the data:

variance(x) = sum((x - E(x))^2) / (size - correction)

Args:

  • src (NDBuffer): The buffer.
  • mean_value (Scalar): The mean value of the buffer.
  • correction (Int): Normalize variance by size - correction.

Returns:

Scalar: The variance value of the elements in a buffer.

Raises:

If the operation fails.

variance[dtype: DType, input_fn_1d: fn[dtype_: DType, width: Int](idx: Int) capturing -> SIMD[dtype_, width]](length: Int, mean_value: Scalar[dtype], correction: Int = 1) -> Scalar[dtype]

Computes the variance of values generated by a function.

Variance is calculated as: variance(X)=i=0length1(XiE(Xi))2sizecorrection\operatorname{variance}(X) = \frac{ \sum_{i=0}^{length-1} (X_i - \operatorname{E}(X_i))^2}{size - correction} where E represents the deviation of a sample from the mean.

This version takes the mean value as an argument to avoid a second pass over the data.

Parameters:

  • dtype (DType): The data type of the elements.
  • input_fn_1d (fn[dtype_: DType, width: Int](idx: Int) capturing -> SIMD[dtype_, width]): A function that generates SIMD values at each index.

Args:

  • length (Int): The number of elements.
  • mean_value (Scalar): The pre-computed mean value.
  • correction (Int): Normalize variance by size - correction (default: 1 for sample variance).

Returns:

Scalar: The variance value.

Raises:

If length is less than or equal to correction.

variance(src: NDBuffer[dtype, 1, origin], correction: Int = 1) -> Scalar[dtype]

Computes the variance value of the elements in a buffer.

variance(x) = sum((x - E(x))^2) / (size - correction)

Args:

  • src (NDBuffer): The buffer.
  • correction (Int): Normalize variance by size - correction (Default=1).

Returns:

Scalar: The variance value of the elements in a buffer.

Raises:

If the operation fails.

variance[dtype: DType, input_fn_1d: fn[dtype_: DType, width: Int](idx: Int) capturing -> SIMD[dtype_, width]](length: Int, correction: Int = 1) -> Scalar[dtype]

Computes the variance of values generated by a function.

This version computes the mean automatically in a first pass.

Parameters:

  • dtype (DType): The data type of the elements.
  • input_fn_1d (fn[dtype_: DType, width: Int](idx: Int) capturing -> SIMD[dtype_, width]): A function that generates SIMD values at each index.

Args:

  • length (Int): The number of elements.
  • correction (Int): Normalize variance by size - correction (default: 1 for sample variance).

Returns:

Scalar: The variance value.

Raises:

If length is less than or equal to correction.

Was this page helpful?