Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused with size of long and double [duplicate]

Looking at Java (but probably similar or the same in other languages), a long and a double both use 8 bytes to store a value.

A long uses 8 bytes to store long integers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

A double uses 8 bytes to store double-precision, floating-point numbers from -1.7E308 to 1.7E308 with up to 16 significant digits.

My question is, if both use the same number of bytes (8 bytes or 2^64), how can double store a much longer number? 1.7E308 is a hell of a lot larger than 9,223,372,036,854,775,807.

like image 710
user2662723 Avatar asked Sep 08 '13 17:09

user2662723


2 Answers

The absolute quantity of information that you can store in 64 bit is of course the same.

What changes is the meaning you assign to the bits.

In an integer or long variable, the codification used is the same you use for decimal numbers in your normal life, with the exception of the fact that number two complement is used, but this doesn't change that much, since it's only a trick to gain an additional number (while storing just one zero instead that a positive and a negative).

In a float or double variable, bits are split in two kinds: the mantissa and the exponent. This means that every double number is shaped like XXXXYYYYY where it's numerical value is something like XXXX*2^YYYY. Basically you decide to encode them in a different way, what you obtain is that you have the same amount of values but they are distribuited in a different way over the whole set of real numbers.

The fact that the largest/smallest value of a floating number is larger/smaller of the largest/smalles value of a integer number doesn't imply anything on the amount of data effectively stored.

like image 127
Jack Avatar answered Sep 28 '22 05:09

Jack


A double can store a larger number by having larger intervals between the numbers it can store, essentially. Not every integer in the range of a double is representable by that double.

More specifically, a double has one bit (S) to store sign, 11 bits to store an exponent E, and 52 bits of precision, in what is called the mantissa (M).

For most numbers (There are some special cases), a double stores the number (-1)^S * (1 + (M * 2^{-52})) * 2^{E - 1023}, and as such, when E is large, changing M by one will make a much larger change in the size of the resulting number than one. These large gaps are what give doubles a larger range than longs.

like image 44
qaphla Avatar answered Sep 28 '22 05:09

qaphla