Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Math.average #1170

Merged
merged 2 commits into from Aug 13, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 8 additions & 0 deletions contracts/math/Math.sol
Expand Up @@ -13,4 +13,12 @@ library Math {
function min(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a < _b ? _a : _b;
}

function average(uint256 _a, uint256 _b) internal pure returns (uint256) {
// (_a + _b) / 2 can overflow, so we distribute
uint256 c = (_a / 2) + (_b / 2) + ((_a % 2 + _b % 2) / 2);
assert((_a <= c && c <= _b) || (_a >= c && c >= _b));
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@leonardoalt how do you feel about these sort of assertions? Do you consider them necessary and correct, or do you think they may add too much unnecessary overhead (and gas costs)?


return c;
}
}
4 changes: 4 additions & 0 deletions contracts/mocks/MathMock.sol
Expand Up @@ -12,4 +12,8 @@ contract MathMock {
function min(uint256 _a, uint256 _b) public pure returns (uint256) {
return Math.min(_a, _b);
}

function average(uint256 _a, uint256 _b) public pure returns (uint256) {
return Math.average(_a, _b);
}
}
30 changes: 30 additions & 0 deletions test/library/Math.test.js
@@ -1,5 +1,11 @@
const MathMock = artifacts.require('MathMock');

const BigNumber = web3.BigNumber;

require('chai')
.use(require('chai-bignumber')(BigNumber))
.should();

contract('Math', function () {
const min = 1234;
const max = 5678;
Expand Down Expand Up @@ -31,4 +37,28 @@ contract('Math', function () {
assert.equal(result, 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));
});
});
});