The variance function in the Statistics library calculates the variance of an array of non-negative uint256 values, but due to Solidity’s lack of floating-point support, results may be imprecise.
1. The function may return zero variance for non-identical data points. For instance, an input of [1,2,3]
yields a variance of 0 due to the integer division rounding error in Solidity.
avg([1,2,3])
results in 2
, and the computed variance is ( (1-2)^2 + (2-2)^2 + (3-2)^2 ) / 3
, which approximates to zero in integer division.
2. Solidity's lack of floating-point precision leads to the truncation of calculated variance to the nearest integer. For example, the variance of [1, 2, 3, 5] is theoretically 2.6666 but is truncated to 2.
3. When calculating the difference between data[i]
and mean
, a potential underflow may occur if data[i] < mean
, resulting in an erroneous large number due to uint256
wraparound.
This function may produce misleading results
Manual Review
Use Absolute Differences:
Apply a check to ensure that diff
is calculated as diff = data[i] >= mean ? data[i] - mean : mean - data[i];
to avoid potential underflows.
Recalculate with Enhanced Precision:
Implement a workaround for floating-point precision, such as scaling values before calculations and scaling them down afterward, to approximate decimals.
Add Edge Case Checks:
Verify that variance values make logical sense, particularly checking for zero variance cases and non-zero data points.
The contest is live. Earn rewards by submitting a finding.
This is your time to appeal against judgements on your submissions.
Appeals are being carefully reviewed by our judges.