Math.average (#1170)

* Added Math.average

* Removed assertion.
pull/1197/head^2
Nicolás Venturo 7 years ago committed by GitHub
parent e493d2a6ba
commit d51e38758e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 5
      contracts/math/Math.sol
  2. 4
      contracts/mocks/MathMock.sol
  3. 24
      test/library/Math.test.js

@ -13,4 +13,9 @@ library Math {
function min(uint256 _a, uint256 _b) internal pure returns (uint256) { function min(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b; return _a < _b ? _a : _b;
} }
function average(uint256 _a, uint256 _b) internal pure returns (uint256) {
// (_a + _b) / 2 can overflow, so we distribute
return (_a / 2) + (_b / 2) + ((_a % 2 + _b % 2) / 2);
}
} }

@ -12,4 +12,8 @@ contract MathMock {
function min(uint256 _a, uint256 _b) public pure returns (uint256) { function min(uint256 _a, uint256 _b) public pure returns (uint256) {
return Math.min(_a, _b); return Math.min(_a, _b);
} }
function average(uint256 _a, uint256 _b) public pure returns (uint256) {
return Math.average(_a, _b);
}
} }

@ -37,4 +37,28 @@ contract('Math', function () {
result.should.be.bignumber.equal(min); result.should.be.bignumber.equal(min);
}); });
}); });
describe('average', function () {
function bnAverage (a, b) {
return a.plus(b).div(2).truncated();
}
it('is correctly calculated with two odd numbers', async function () {
const a = new BigNumber(57417);
const b = new BigNumber(95431);
(await this.math.average(a, b)).should.be.bignumber.equal(bnAverage(a, b));
});
it('is correctly calculated with two even numbers', async function () {
const a = new BigNumber(42304);
const b = new BigNumber(84346);
(await this.math.average(a, b)).should.be.bignumber.equal(bnAverage(a, b));
});
it('is correctly calculated with one even and one odd number', async function () {
const a = new BigNumber(57417);
const b = new BigNumber(84346);
(await this.math.average(a, b)).should.be.bignumber.equal(bnAverage(a, b));
});
});
}); });

Loading…
Cancel
Save