Harmonic Mean

The harmonic mean is a useful function for calculating effective interest rates or the rate of return in financial applications. Additionally, it is often used for averaging ratios or rates, such as in the F-measure for evaluating classification models. The formal definition is defined below.

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

To implement the Harmonic mean function, see the method signature below.

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

Precision represents the number of decimal places and can be set between 0 and 18. It is applied to nums, weights and the output. Under the hood, the following functions are utilized directly in the Neural client.

func (con *NeuralMath) HarmonicMean(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.HarmonicMean(floats, w) * mul).Int(&mean)
	return &mean, nil, nil
}

Last updated