ios - Converting Int to Float loses precision for large numbers in Swift -


xcode 6.3.1 swift 1.2

let value: int = 220904525 let intmax = int.max let float = float(value) // here error let intfromfloat = int(float) let double = double(value) println("intmax=\(intmax) value=\(value) float=\(float) intfromfloat=\(intfromfloat) double=\(double)") // intmax=9223372036854775807 value=220904525 float=2.20905e+08 intfromfloat=220904528 double=220904525.0 

the initial value 220904525. when convert float becomes 220904528. why?

this due way floating-point format works. float 32-bit floating-point number, stored in ieee 754 format, scientific notation, bits allocated value, , exponent (in base 2), diagram single-precision floating-point number wikipedia article shows:

32-bit float format

so actual number represented as

(sign) * (value) * (2 ^ (exponent)) 

because number of bits allocated storing integer value (24) smaller number of bits allocated in normal integer (all 32), in order make room exponent, less significant digits of large numbers sacrificed, in exchange ability represent infinite numbers (a normal int can represent integers in range -2^31 2^31 - 1).

some rough testing indicates every integer , including 16777216 (2 ^ 24) can represented exactly in 32-bit float, while larger integers rounded nearest multiple of power of 2.

note isn't specific swift. floating-point format standard format used in every programming language. here's output lldb plain c:

if need higher precision, use double. double precision floats use 64 bits of memory, , have higher precision.


Comments

Popular posts from this blog

c++ - Difference between pre and post decrement in recursive function argument -

php - Nothing but 'run(); ' when browsing to my local project, how do I fix this? -

php - How can I echo out this array? -