是否有可能在JavaScript中没有舍入问题的情况下实现任意精度算术? [英] Is it possible to achieve arbitrary-precision arithmetic with no rounding issues in JavaScript?

查看:82
本文介绍了是否有可能在JavaScript中没有舍入问题的情况下实现任意精度算术?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过big.js,bignumber.js和decimal.js;它们在某一点上工作得相当好,但是当我需要使用足够大的奇数数字进行任意精度计算时(我目前的测试用例是 31435517643980 *(1/31435517643980) )=== 1 )。我对任何允许我处理这样的表达式的解决方案持开放态度,包括对外部API的调用。我目前正在查看Wolfram | Alpha的API,但2000个电话/月限制是我想避免的限制,因为我的应用程序将进行相当多的调用。

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.

如果这是这个问题的错误的SE网站,请告诉我和/或移动它。

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

推荐答案

可能最常见的方法是将两个数字乘以相同的乘数,使它们没有小数,然后再进行操作,再划分。这是一个粗略的实现:

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));
}

然后,运行 xNums(31435517643980,(1 / 31435517643980))=== 1 。适用于我的Chrome

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

这篇关于是否有可能在JavaScript中没有舍入问题的情况下实现任意精度算术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆