Mihir Mehta
Mihir Mehta

Reputation: 13843

Foundation: Why Int64.max and Double(Int64.max) prints 2 entire different value in Swift iOS SDK

Here is my Swift Code

print("\(Int64.max)")
print("\(Double(Int64.max))")

It produce following output

9223372036854775807

9.223372036854776e+18

Why the both value is entire different 9.223372036854776e+18 - 9223372036854775807 = 193 FYI

Upvotes: 2

Views: 966

Answers (1)

Sweeper
Sweeper

Reputation: 272770

The value of Double you are seeing in the output is only an approximation to some number of significant figures. We can see more significant figures by String(format:)

print(String(format: "%.1f", Double(Int64.max)))

This prints:

9223372036854775808.0

So actually, the difference is not as big as what you claimed it was (193). It's just a difference of 1.

Why is there a difference?

Double stores value using a floating point representation. It can represent a wide range of numbers, but not every number in that range. Double uses 53 bits of mantissa, 1 sign bit and 11 bits to store the exponent. The mantissa represents the significant digits of the number, and the exponent tells you where to put the decimal point. Everything on one side of the decimal point represents positive powers of 2 and everything on the other side represent negative powers of 2. For example:

0.1010000    0010
  mantissa    exponent

The exponent says to move the decimal point to the right 3 times, so the mantissa becomes 010.10000. The 1 on the left represents 2, and the 1 on the right represents a half (2^-1), so this floating point number represents the number 2.5

To represent Int64.max (2^63-1), you need 63 bits of mantissa to all be 1s and the value in the exponent to be 63. But Double does not have that many bits of mantissa! So it can only approximate. Int64.max + 1 is actually representable by a Double, because it is equal to 2^63. You just need one 1 followed by 52 0s in the mantissa and the exponent can store 64. And that's what Double did.

Upvotes: 5

Related Questions