Dria

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

Precision Loss Due to Integer Division

Location : contracts/libraries/Statistics.sol

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; // Integer division truncates the result, causing precision loss
}
  • Problem: Solidity only supports integer division, which truncates any fractional part. When calculating the mean (sum / data.length), this results in precision loss, especially noticeable in arrays where the true mean is a non-integer.

  • Recommendation: If higher precision is necessary, consider scaling the sum before division or using a fixed-point library to approximate decimal precision. Otherwise, document this limitation clearly.

  • Tools used: Github and VSC

  • POC:

uint256;
values[0] = 1;
values[1] = 1;
values[2] = 2;
uint256 avgResult = Statistics.avg(values); // Expected truncated result
  • Expected Outcome: avgResult will yield 1 instead of the true mean of 1.333, demonstrating precision loss due to truncation.

  • Impact: Results in approximations rather than exact values, which might affect statistical calculations relying on high precision, particularly when working with small datasets or when calculating thresholds based on mean or variance.

Updates

Lead Judging Commences

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

Support

FAQs

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