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.
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.
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.
Manual
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.
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.