Why does Swift use base 2 to measure floating point hexadecimal values?

According to Swift Programming Language:

For example, 0xFp2 represents 15 ⨉ 2 ^ 2, which corresponds to 60. Similarly, 0xFp-2 represents 15 ⨉ 2 ^ (- 2), which is 3.75.

Why is 2 used as the basis for the indicator instead of 16? I would expect 0xFp2 == 15 * (16**2) instead of 0xFp2 == 15 * (2**2)

+6
source share
1 answer

The Swift hexadecimal notation for floating point numbers is just a variation of the notation introduced for C in the C99 standard for input and output (with printf %a format).

The purpose of this notation is to both be easily interpreted by people and to allow bits of representation

The number 0x1.91eb851eb851fp+1 can be seen just above 3, because the indicator is 1 , and the value is about 0x1.9 , just above 0x1.8 , which indicates the exact middle between two degrees of two.

This format helps to remember that numbers that have a compact representation in decimal format are not necessarily simple in binary format. In the above example, 3.14 uses all digits of the sign for approximation (and even in this case it is not represented exactly).

Hexadecimal is used for the number before p , which corresponds to an IEEE 754 value because it is more compact than binary. IEEE 754 binary value requires 13 hexadecimal digits after 0x1. to represent completely, that much, but in binary format, 52 digits will be required, which is frankly impractical.

The choice of a hexadecimal number actually has its drawbacks: because of this choice, several equivalent representations for the same number are not always easy to recognize as equivalent. For example, 0x1.3p1 and 0x2.6p0 represent the same number, although their numbers have nothing in common. In binary format, the two entries would correspond to 0b1.0011p1 and 0b10.011p0 , which would be easier to see as equivalent. To take another example, 3.14 can also be represented as 0xc.8f5c28f5c28f8p-2 , which is extremely difficult to see as the same number as 0x1.91eb851eb851fp+1 . This problem would not exist if the number after p represented a power of 16, as you suggest in your question, but the unity of presentation was not the goal when C99 was standardized: the proximity to the IEEE 754 presentation was.

+10
source

Source: https://habr.com/ru/post/971501/


All Articles