Arithmetic Mean

The arithmetic mean is widely used in financial engineering for calculating averages of asset returns, prices, and other financial metrics. In machine learning, it is a fundamental operation for calculating the central tendency of data, which is essential for many algorithms and models.

AM(x1,x2,,xn)=1ni=1nxi\operatorname{AM}(x_1, x_2, \ldots, x_n) = \frac{1}{n}\sum_{i=1}^n x_i

To implement the Mean function, see the method signature below. Precision represents the number of decimal places and can be set between 0 and 18. It is applied to nums, weights and the output.

function Mean(int256[] calldata nums, uint256[] calldata weights, uint8 precision) external returns (int256);

Under the hood, the following functions are utilized directly in the Neural client.


func (con *NeuralMath) Mean(gas *big.Int, nums []*big.Int, weights []*big.Int, precision uint8) (*big.Int, error, *big.Int) {
	mul, err := validatePrecision(precision)
	if err != nil {
		return nil, err, nil
	}

	if len(nums) != len(weights) {
		return nil, errors.New("len(nums) != len(weights)"), nil
	}
	w, err := toFloats(weights, mul)
	if err != nil {
		return nil, err, nil
	}
	floats, err := toFloats(nums, mul)
	if err != nil {
		return nil, err, nil
	}
	var mean big.Int
	big.NewFloat(stat.Mean(floats, w) * mul).Int(&mean)
	return &mean, nil, nil
}

Last updated