It's kinda hard to believe -- but I can't find info about the largest possible integer allowed in node.js, in either Google or SO. There are plenty of articles on the largest integer in browser Javascript, but I just wonder things could be different in node.js.
Can anyone give some pointer? Thanks!
There are plenty of articles on the largest integer in browser Javascript, but I just wonder things could be different in node.js.
No. JavaScript is JavaScript, a language defined by specification. So the answers you find for "browser JavaScript" also apply to NodeJS.
The maximum integer value that can be represented by a IEEE-754 double-precision binary floating point number (the kind JavaScript uses) is 1.7976931348623157 x 10308, which is available in JavaScript as Number.MAX_VALUE.
The maximum integer that you can reliably add 1 to and not get the same value back due to a loss of precision is Number.MAX_SAFE_INTEGER, which is 9,007,199,254,740,991. That is, 9007199254740991 + 1 is 9007199254740992, but 9007199254740992 + 1 is also 9007199254740992. There are much larger integers that can be held (see above), but the gaps between them grow as the value increases.
Related
This question already has answers here:
Is floating point math broken?
(31 answers)
Closed 3 years ago.
Using the parseFloat method converted the string value from the DB to float and multiplied by 100. But the output looks odd. Following the piece of code which I've used.
parseFloat(upliftPer) * 100 //upliftPer value read from DB and its value is 0.0099
So when it multiplied with 100 getting 0.9900000000000001 I suppose to get 0.99 but some junk values getting appended. Also I went ahead and did the same in the console log of chrome browser still the same result. I have attached screenshots for reference. Solution I needed is 0.0099 * 100 should result 0.99. I cant apply round / toFixed since I need more precision.
This is because of JavaScript internal casting to double type. There's always a certain degree of noise due to floating point inaccuracy. Here's some information on that.
You can just round it up using toFixed(x) with as much decimal spaces of precision as you want (or as much as JavaScript would allow you).
It is not related to JavaScript nor to any programming language.
It’s because of the conversion from decimal floating-point to binary representation: the process ends up in an infinite process that has to be truncated because of the limited number of bits available for storing the numbers (and thus, of the limited amount of memory in computers)
Check out the process of conversion and take a look at this converter that tells you how much error there is during conversion
As #sebasaenz pointed out in his answer, you can use toFixed(x) to round up your number and get rid of junk
As the question here states, even the newest Ecmascript 8 has no support for 64bit integers.
But the stage 3 proposal for bigInt looks promising and I expect it will be added to the Js spec sometime soon.
However, Even according to the proposal, we have to use a special constructor for declaring big numbers. (Q1) What is the technical reason behind, being unable to represent big numbers in the general way?
let bigNum = 2 ** 64 // Why can't JS do this without losing precision? (at least in future)
I know that JavaScript represents all numbers using IEEE-754 double-precision (64 bit) floating points and that this causes the problem.
(Q2) Why can't Javascript represent all numbers using some other standard which doesn't lose precision?
(Q3) What complications would arise if Javascript actually did that?
Edit: As stated by T.J, we can use a suffix instead of a constructor, but I still feel that is not exactly the general notation
(Q1) What is the technical reason behind, being unable to represent big numbers in the general way?
Breaking the web. The fundamentals of JavaScript numbers cannot be changed now, 20-odd years after they were originally defined. There's also the issue of performance: JavaScript's current numbers (IEEE-754 binary double [64-bit] precision) are very fast floating point thanks to being built into CPUs and math coprocessors. The cost of that speed is precision; the cost of arbitrary precision (or a dramatically larger precise range) is performance.
Someday in the future, perhaps JavaScript will get IEEE-754 64-bit or even 128-bit decimal floating point numbers (see here and here), if those formats (introduced in 2008) diffuse into the ecosystem and get hardware support. But that's speculation on my part. :-)
(Q2) Why can't Javascript represent all numbers using some other standard which doesn't lose precision?
See Q1. :-)
(Q3) What complications would arise if Javascript actually did that?
See Q1. :-)
Even according to the proposal, we have to use a special constructor for declaring big numbers.
If you want 64-bit specifically. If you just want BigInts, the proposal includes a new notation, the n suffix, for that: 2n is a BigInt 2. So with BigInts, your example would be
let bigNum = 2n ** 64n;
In JavaScript, there's only one type for all different kinds of numbers. Does the amount of decimals in the numbers used (precision) affect performance especially in JavaScript? If it does, how?
How about saving numbers in MongoDB: Do precise numbers take more space than less precise ones?
Generally no. There are some possible performance implications when a number doesn't fit in a 31b signed int.
A tour of V8: object representation explains
According to the spec, all numbers in JavaScript are 64-bit floating point doubles. We frequently work with integers though, so V8 represents numbers with 31-bit signed integers whenever possible (the low bit is always 0; this helps the garbage collector distinguish numbers from pointers). So objects with the fast small integers elements kind only contain this type of number. If we want to store a fractional number or a larger integer or a special value like -0, then we need to upgrade the array to fast doubles. This involves a potentially expensive copy-and-convert operation, but it doesn't happen often in practice. fast doubles objects are still pretty fast because all of the numbers are stored in an unboxed representation. If we want to store any other kind of value, e.g., a string or an object, we must upgrade to a general array of fast elements.
Does the amount of decimals in the numbers used (precision) affect performance especially in JavaScript? If it does, how?
No. The number type in JavaScript is a 64-bit floating-point value with base 2 and always has the same precision. The computer works on that data bit by bit and it doesn't matter whether that data represents something that looks simple to a human like 1.0 or something seemingly complicated like 123423.5645632. In fact, for base 2 floats, the 'human' values are just as 'hard', because 1.1 is truly represented by a much longer number (sth. like 1.10000000000000054). All this doesn't matter, because the computer truly operates on 64 ones and zeros. There are always some arcane exceptions in floating point, but those usually don't matter in practice.
How about saving numbers in MongoDB: Do precise numbers take more space than less precise ones?
Decimal numbers are stored as doubles (64bit), and it doesn't matter whether that is 1.0 or 1.1221234423. Again, the number of bits is constant for these data types.
The same is true for ints, but MongoDB has support for both 32- and 64-bit ints. So NumberLong is indeed larger than regular 32-bit ints and just as large as doubles.
I found a VB script in an Excel file that implements Runge-Kutta integration for solving a differential equation. I converted the implementation line by line to Javscript. However, the Javascript program does not yield the exact same results as the VB one... The numbers are close enough to be marginally acceptable, but I trust that the VB implementation is correct as it was part of a PhD Dissertation. So this leads me to believe that my Javascript implementation, running on NodeJS, suffers from some rounding ghosts.
In particular, I have noticed that as I continually add 0.01 to my time counter, the values are eventually unable to be represented properly, and I get values like 5.299999999999999934 instead of 5.3. This makes sense to me, as I have read about this quirk of Javascript in some books.
My Questions Are
Is my observation correct that Visual Basic does not suffer from this same precision shortcoming?
Does this mean plain vanilla Javascript math is inherently less accurate than plain vanilla VB math? (Without using other math libraries).
If I clamp my time variable, as in, force the value to be 5.30, instead of 5.299999999, will this actually make my results more correct?
edit: Using a Math.round(X*100)/100 clamp changes the output of all my time values to have only 2 decimal places, but does not actually change the values of any computations.
JavaScript uses IEEE 754 double-precision floating-point numbers...just like Visual Basic. The only difference is that JavaScript uses doubles for all numbers (that is, it doesn't have an integer type, or a single-precision float).
If a calculation in VB uses numbers of type Double in its calculations, it should have the same accuracy and precision as the equivalent calculation in JavaScript.
The upshot is that VB is in no way more accurate with respect numerical calculations than JavaScript. Whenever you're dealing with floating-point values, though, you have to be careful.
You should probably read David Goldberg's excellent article, What Every Computer Scientist Should Know About Floating-Point Arithmetic.
The chance of errors multiplying is increased with the number of summations, and there are a LOT of summations in techniques like Runge-Kutta, so the algorithm has to be constructed very carefully to take this into account. The definitive book on the subject is the time-tested Numerical Recipes, which covers Runge-Kutta, and takes into account floating-point errors.
I'm currently writing a compiler for a small language that compiles to JavaScript. In this language, I'd quite like to have integers, but JavaScript only supports Number, which is a double-precision floating point value. So, what's the most efficient way to implement integers in JavaScript? And how efficient is this compared to just using Number?
In particular, overflow behaviour should be consistent with other languages: for instance, adding one to INT_MAX should give INT_MIN. Integers should either be 32-bit or 64-bit.
So, what's the most efficient way to implement integers in JavaScript?
The primitive number type is as efficient as it gets. Many modern JS engines support JIT compilation, so it should be almost as efficient as native floating-point arithmetic.
In particular, overflow behaviour should be consistent with other languages: for instance, adding one to INT_MAX should give INT_MIN. Integers should either be 32-bit or 64-bit.
You can achieve the semantics of standard 32-bit integer arithmetic by noting that JavaScript converts "numbers" to 32-bit integers for bitwise operations. >>> (unsigned right shift) converts its operand to an unsigned 32-bit integer while the rest (all other shifts and bitwise AND/OR) convert their operand to a signed 32-bit integer. For example:
0xFFFFFFFF | 0 yields -1 (signed cast)
(0xFFFFFFFF + 1) | 0 yields 0 (overflow)
-1 >>> 0 yields 0xFFFFFFFF (unsigned cast)
I found this implementation of BigIntegers in Javascript: http://www-cs-students.stanford.edu/~tjw/jsbn/
Perhaps this will help?
Edit: Also, the Google Closure library implements 64-bit integers:
http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/math/long.js
These are essentially just generating convenience objects though, and won't do anything for improving on the fundamental data-type efficiency.
On a modern CPU if you restrict your integer values to the range +- 2^52 then using a double will be barely less efficient than using a long.
The double IEE754 type has 53 bits of mantissa, so you can easily represent the 32-bit integer range and then some.
In any event, the rest of Javascript will be much more of a bottleneck than the individual CPU instructions used to handle arithmetic.
All Numbers are Numbers. There is no way around this. JavaScript has no byte or int type. Either deal with the limitations or use a more low level language to write your compiler in.
The only sensible option if you want to achieve this is to edit one of the JavaScript interpreters (say V8) and extend JS to allow access to native C bytes.
Well you can choose JavaScript's number type which is probably computed using primitives of your CPU or you can choose to layer a complete package of operators and functions and what not on an emulated series of bits...?
... If performance and efficiency is your concern, stick with the doubles.
The most efficient would be to use numbers, and add operations to make sure that operations on the simulated integers would give an integer result. A division for example would have to be rounded down, and a multiplication would either have to be checked for overflow or masked down to fit in the integer range.
This of course means that floating point operations in your language will be considerably faster than integer operations, defeating most of the purpose of having an integer type in the first place.
Note that ECMA-262 Edition 3 added
Number.prototype.toFixed, which takes
a precision argument telling how many
digits after the decimal point to
show. Use this method well and you
won't mind the disparity between
finite precision base 2 and the
"arbitrary" or "appropriate" precision
base 10 that we use every day.
- Brendan Eich