frozeman / bignumber.js-nolookahead

BigNumber.js version with no look ahead regex for web3.js 0.x.x
MIT License
10 stars 20 forks source link

Division is not calculated correctly #1

Open peculiarity opened 7 years ago

peculiarity commented 7 years ago

Hey @frozeman

Since this is the version that is used in web3js I'm creating the issue in here. I have the following case.

let dividend = new BigNumber(3000000000000000000);
let divisor = new BigNumber(3702000000000000000);
dividend.div(divisor).times(divisor).toString(10);
// "2999999999999999999.98416"

image

The result should be 3000000000000000000

There is also a different case doing the same calculation. The order of operations is reverted.

let dividend = new BigNumber(3000000000000000000);
let divisor = new BigNumber(3702000000000000000);
dividend.times(divisor).div(divisor).toString(10);
// "3000000000000000000"

image

The result is indeed 3000000000000000000

Theoretically the results shouldn't differ.

MikeMcl commented 6 years ago

@peculiarity

Division is calculated correctly.

The results differ because the divisor doesn't exactly divide the dividend, i.e. the mathematical result of dividend / divisor has an infinite number of decimal places.

In this library, multiplication is always exact, but division is only performed to a specific number of DECIMAL_PLACES. So the accuracy of the result depends on that.

BigNumber.config({ DECIMAL_PLACES: 40 });
let dividend = new BigNumber('3000000000000000000');
let divisor = new BigNumber('3702000000000000000');
dividend.div(divisor).times(divisor).toString();
// "3000000000000000000.0000000000000000000001296"

dividend.div(divisor).times(divisor).round(20).toString();
// "3000000000000000000"