admin管理员组文章数量:1391047
I'm trying to add up a large number but it's not ing out correctly.
var searchSpace = 36;
var length = 11;
var binations = 0;
for(var i = 1; i <= length; i++) {
binations += Math.pow(searchSpace, i);
}
The variable binations
ends up being 135,382,323,952,046,190 which is not quite correct. It should be 135,382,323,952,046,196 (how is it off by 6?!) Any ideas?
I'm trying to add up a large number but it's not ing out correctly.
var searchSpace = 36;
var length = 11;
var binations = 0;
for(var i = 1; i <= length; i++) {
binations += Math.pow(searchSpace, i);
}
The variable binations
ends up being 135,382,323,952,046,190 which is not quite correct. It should be 135,382,323,952,046,196 (how is it off by 6?!) Any ideas?
- 2 A good explanation of "Javascript doesn't have 'integers' - only floating point numbers": developer.mozilla/en/JavaScript/… – paulsm4 Commented Jun 15, 2012 at 4:21
2 Answers
Reset to default 7JavaScript uses IEEE-754 64-bit doubles as its number format. These cannot represent arbitrarily precise values; they bee incorrect when you exceed a certain threshold and begin instead storing values that are close to (but not quite exactly) the actual values. According to this earlier answer, the largest value that can be stored accurately is 253, which is about 9 × 1015. Your number (which is about 1.3 × 1017) is larger than this, so (with good probability) it cannot be represented accurately.
If you want to get the exact answer in JavaScript, you will need to use a library that supports arbitrary-precision integers. A quick Google search turned up this library, but I can't vouch for how accurate it is.
Hope this helps!
All numbers in Javascript are actually floating point numbers. You're dealing with very large numbers, and doing multiple manipulations on those numbers. The inherent errors in dealing with floats pile up quickly in this case, causing the "error".
Being off by 6 on a number that large is actually pretty good. You're off by only 0.000000000000004431%, roughly
本文标签: mathJavaScript not adding large numbers correctly (but getting very close)Stack Overflow
版权声明:本文标题:math - JavaScript not adding large numbers correctly (but getting very close) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744596361a2614801.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论