Dria

Swan
NFTHardhat
21,000 USDC
View results
Submission Details
Severity: low
Invalid

Mean Calculation issue in Statistics Library

Summary

This report examines a potential vulnerability in the Statistics Solidity library, specifically in the avg function, which calculates the mean of an array of uint256 numbers. The calculation performs integer division, which may lead to precision loss in cases where the mean value is a fraction. This inaccuracy can cascade, affecting the accuracy of subsequent calculations in the variance and stddev functions, potentially leading to incorrect statistical outputs.

Vulnerability Details

function avg(uint256[] memory data) internal pure returns (uint256 ans) {
uint256 sum = 0;
for (uint256 i = 0; i < data.length; i++) {
sum += data[i];
}
ans = sum / data.length;
}

The avg function uses integer division (sum / data.length). In cases where sum is small or not perfectly divisible by data.length, integer division will truncate the result, resulting in precision loss. For example, if data contains [0, 1], sum will be 1, and sum / data.length will return 0 instead of the expected 0.5.

Impact

Data Inaccuracy: The variance and stddev functions will produce inaccurate outputs when the mean is truncated to zero or any other incorrect integer value. For instance, when avg returns 0 instead of 0.5 for [0, 1], the variance function’s calculation (data[i] - mean)^2 will be inaccurate for each element, leading to an incorrect overall variance.

Tools Used

Manual

Recommendations

Implement a scaling mechanism where sum is multiplied by a factor (e.g., 10**18) before division. The result can be downscaled post-calculation. This approach maintains higher precision during intermediate calculations.

Updates

Lead Judging Commences

inallhonesty Lead Judge 7 months ago
Submission Judgement Published
Invalidated
Reason: Known issue

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.