Is it possible to achieve arbitrary-precision arithmetic with no rounding issues in JavaScript?

安稳与你 提交于 2019-12-31 02:21:07

问题


I've tried big.js, bignumber.js, and decimal.js; they all work reasonably well up to a certain point, but fall short when I need to do arbitrary-precision calculations with large enough numbers of "odd" digits (my current test case is 31435517643980 * (1 / 31435517643980) === 1). I am open to any solution that allows me to process expressions like this, including calls to an external API. I'm currently looking at Wolfram|Alpha's API, but the 2000 calls/month limit is a restriction I'd like to avoid, because my application is going to be making quite a few calls.

If this is the wrong SE site for this question, please let me know and/or move it.


回答1:


Possibly the most common way to do this is simply multiply both numbers by the same multiplier to make them have no decimals, and then do the operation, then divide again. Here's a crude implementation:

function getDigits(n){
    return n.toString().substring(n.toString().indexOf('.')+1).length;
}
function xNums(n1,n2){
    var highRes=(n1*Math.pow(10,getDigits(n1))*(n2*Math.pow(10,getDigits(n2))));
    return highRes/Math.pow(10,getDigits(n1))/Math.pow(10,getDigits(n2));
}

Then, run xNums(31435517643980,(1 / 31435517643980))===1. Works for me in Chrome



来源:https://stackoverflow.com/questions/28248683/is-it-possible-to-achieve-arbitrary-precision-arithmetic-with-no-rounding-issues

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!