Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Numbers in Javascript and effective range

Tags:

javascript

All numbers in Javascript are 64bit (8 bytes) floating point numbers but why the effective range of JavaScript is 5e-324 (negative) to 1.7976931348623157e+308 (positive)?

like image 640
edwardpku Avatar asked Apr 30 '12 15:04

edwardpku


People also ask

What is the range for JavaScript numbers?

Description. The MAX_SAFE_INTEGER constant has a value of 9007199254740991 (9,007,199,254,740,991, or ~9 quadrillion). Double precision floating point format only has 52 bits to represent the mantissa, so it can only safely represent integers between -(253 – 1) and 253 – 1.

How do you check if a number lies in a range in JavaScript?

To check if a number is between two numbers: Use the && (and) operator to chain two conditions. In the first condition check that the number is greater than the lower range and in the second, that the number is lower than the higher range. If both conditions are met, the number is in the range.

Can you use range in JavaScript?

JavaScript Range is a function that is supported by JavaScript in order to return all the integer and its value from starting to the ending while traversing from start index to the end index.

How do you check if a number is between a range?

If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range.


2 Answers

Because that is what is defined by the IEEE 754 spec.

0x 0000 0000 0000 0001 = 2⁻¹⁰²²⁻⁵² ≈ 4.9406564584124654 x 10⁻³²⁴ (Min subnormal positive double)
0x 000f ffff ffff ffff = 2⁻¹⁰²² - 2⁻¹⁰²²⁻⁵² ≈ 2.2250738585072009 x 10⁻³⁰⁸ (Max subnormal positive double)
0x 0010 0000 0000 0000 = 2⁻¹⁰²² ≈ 2.2250738585072014 x 10⁻³⁰⁸ (Min normal positive double)
0x 7fef ffff ffff ffff = (1 + (1 - 2⁻⁵²)) x 2¹⁰²³ ≈ 1.7976931348623157 x 10³⁰⁸ (Max Double)
like image 198
Matt Ball Avatar answered Oct 05 '22 05:10

Matt Ball


Because of denormal values; see e.g. http://en.wikipedia.org/wiki/Denormal_number. These extend the range of floating-point values to allow values closer to zero than would otherwise be possible.

You would be well advised to treat these as an implementation detail whose purpose is to make calculations with very small intermediate results not behave too pathologically; when you use these very small values some precision is lost.

like image 44
Gareth McCaughan Avatar answered Oct 05 '22 05:10

Gareth McCaughan