Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

How Are Decimals Represented — Floating Point and IEEE 754

How Are Decimals Represented -- Floating Point and IEEE 754

In this lesson you will understand: how decimals are represented in a world of only 0 and 1, and why floating-point numbers have precision errors.


Real-life analogy: scientific notation

You have surely seen scientific notation in physics class:

Speed of light = 3.0 x 108 m/s, electron mass = 9.1 x 10-31 kg.

This way, very few digits can represent very large or very small numbers.

Computers use exactly the same idea to represent decimals — binary scientific notation.

Any binary fraction can be written as:

1.xxxxxxxxxx x 2yyyyy

This form needs to store only three things:

The IEEE 754 standard packs these three things into 32 bits in a fixed format.


The three-part structure of IEEE 754 single precision

The 32 bits (single-precision float) are divided precisely into three parts:

Sign bit

0

1 bit

Exponent bits

00000000

8 bits

Mantissa bits (Fraction)

00000000000000000000000

23 bits

Sign bit (1 bit)

Exponent (8 bits)

Mantissa (23 bits)

Part 1: the sign bit (1 bit)

The simplest part.

0 Means positive,1 Means negative.

Part 2: the exponent bits (8 bits)

The exponent determines the position of the decimal point (this is where the name "floating point" comes from — the point can "float").

But the exponent is not stored directly; instead we store "actual exponent + 127".

This 127 is called the bias (Bias).

Why add a bias?

Because 8 bits can only represent 0~255 (unsigned), but the actual exponent needs to be negative (to represent numbers smaller than 1).

After adding the bias 127:

Part 3: the mantissa bits (23 bits)

The mantissa stores the "xxxxx" part of "1.xxxxx", omitting the leading 1.

Because in binary scientific notation the normalized form is always 1.xxx, the leading 1 does not need to be stored.

This cleverly saves 1 extra bit of precision.

The key to understanding the three parts: floating point = (-1)^sign before positive numbers x 1.mantissa x 2(exponent-127). This is the entire essence of IEEE 754.


Interactive demo: 32-bit float disassembler

Enter a floating-point number and observe its three-part structure in IEEE 754 single precision.

The segmented bar highlights which bits belong to each of the three parts.

IEEE 754 single-precision disassembler

Enter a float:

Try entering 0.1 and observe the mantissa.

The binary mantissa of 0.1 is an infinitely repeating fraction — 23 bits are far from enough to store it.

This leads to a famous computer phenomenon.


Why 0.1 + 0.2 is not equal to 0.3

If you run in Python or JavaScript 0.1 + 0.2 == 0.3, the result is False.

This is not a bug but an inevitable consequence of floating-point representation.

The reason is simple: 0.1 cannot be represented exactly in binary.

Just as in decimal, 1/3 = 0.33333... is an infinitely repeating fraction.

In binary, 0.1 (decimal) = 0.000110011001100110011... (binary), also an infinitely repeating fraction.

IEEE 754 has only 23 mantissa bits to store this infinitely repeating fraction.

The part beyond 23 bits can only be truncated (rounded), which produces rounding error.

The value actually stored for 0.1 in float32 is about 0.100000001490116119384765625.

The value actually stored for 0.2 in float32 is about 0.20000000298023223876953125.

After adding the two and truncating, the result is not exactly 0.3.

Monetary calculations must avoid floating point

For monetary scenarios, use integers (in units of "cents") or a dedicated Decimal type.

Python's Decimal, Java's BigDecimal, C#'s decimal are all designed for this.

If you store money as floats, by the time you notice the accumulated error of 0.01 has become 0.010000000000000002, the problem was sown long ago.


Range of floating-point values and special values

IEEE 754 reserves several special combinations of exponent and mantissa:

Category Sign bit Exponent (stored) Mantissa Meaning
zero 0 or 1 0 (all 0) All 0 +0 or -0
Denormalized numbers 0 or 1 0 (all 0) Not all 0 Values very close to 0
Normalized numbers 0 or 1 1 ~ 254 Any Normal floating-point numbers
Infinity 0 or 1 255 (all 1) All 0 +Infinity or -Infinity
NaN Any 255 (all 1) Not all 0 Not a Number (e.g., 0/0)

Approximate range of single-precision float (32 bits):

Double precision (64 bits) has a larger range and higher precision:


Three cases of floating-point precision loss

Case 1: conversion error from decimal to binary

As in the 0.1 example above.

Any decimal that looks "clean" in base 10 may be infinitely repeating in binary.

Only fractions whose denominator is a power of 2 (e.g., 0.5, 0.25, 0.125) can be represented exactly in binary.

Case 2: large number plus small number

Floating-point precision is not uniformly distributed — the larger the value, the larger the smallest distinguishable difference.

For example, 16777216.0 + 1.0 = 16777216.0 (unchanged in float32).

Because a 32-bit float can represent only about 7 significant digits exactly, and 16777216 already occupies 8.

The change from adding 1 falls into a precision range the mantissa cannot represent, so it is simply "swallowed".

Case 3: subtracting close numbers

Subtracting two very close floating-point numbers causes catastrophic loss of significant digits.

For example, 1.2345678 - 1.2345677 = 0.0000001, but the actual computation may give a highly erroneous result like 0.000000099999...

Understanding the precision limits of floating point is not to make you "afraid" of it, but to help you choose the right tool for the right scenario. Scientific computing, graphics rendering, machine learning — floats are perfectly adequate there. But finance, accounting, and exact counting — stay away from floats.


Code demo: the secrets of floating point

Example

Full demo of floating-point precision issues (runoob demo)

import

struct

def

float_to_ieee754_binary

(

num

)

:

   

"""Convert a float to the three-part IEEE 754 single-precision representation"""

   

Use struct to pack the float into 4 bytes (big-endian)

    packed

=

struct

.

pack

(

'>f'

,

num

)

   

Convert to a 32-bit binary string

    bits

=

''

.

join

(

f

'{b:08b}'

for

b

in

packed

)

    sign

=

bits

[

0

]

    exponent

=

bits

[

1

:

9

]

    mantissa

=

bits

[

9

:

32

]

    exp_stored

=

int

(

exponent

,

2

)

    exp_actual

=

exp_stored -

127

   

Compute the fractional value of the mantissa

    frac

=

0

   

for

i

,

bit

in

enumerate

(

mantissa

)

:

       

if

bit

==

'1'

:

            frac +

=

2

** -

(

i +

1

)

    value

=

(

1

if

sign

==

'1'

else

1

)

(

1

)

(

2

** exp_actual

)

   

return

{

       

'bits'

: bits

,

       

'sign'

: sign

,

       

'exponent'

: exponent

,

       

'mantissa'

: mantissa

,

       

'exp_stored'

: exp_stored

,

       

'exp_actual'

: exp_actual

,

       

'fraction'

: frac

,

       

'reconstructed'

: value

   

}

=============================================

Demo 1: compare the representations of 0.5 and 0.1

=============================================

print

(

"="

60

)

print

(

"Demo 1: why 0.5 is exact but 0.1 is not"

)

print

(

"="

60

)

for

num

in

[

0.5

,

0.1

]

:

    r

=

float_to_ieee754_binary

(

num

)

   

print

(

f

"\nFloat: {num}"

)

   

print

(

f

" Sign bit: {r['sign']} ({'positive' if r['sign'] == '0' else 'negative'})"

)

   

print

(

f

" Exponent: {r['exponent']} (stored={r['exp_stored']}, actual={r['exp_actual']})"

)

   

print

(

f

" Mantissa: {r['mantissa']}"

)

   

print

(

f

" Actual stored value: {r['reconstructed']}"

)

=============================================

Demo 2: the classic 0.1 + 0.2 != 0.3

=============================================

print

(

"\n"

"="

60

)

print

(

"Demo 2: 0.1 + 0.2 != 0.3"

)

print

(

"="

60

)

Display with higher precision

import

decimal

ctx

=

decimal

.

getcontext

(

)

ctx.

prec

=

50

a

=

decimal

.

Decimal

(

0.1

)

b

=

decimal

.

Decimal

(

0.2

)

c

=

decimal

.

Decimal

(

0.3

)

print

(

f

"0.1 actual value: {a}"

)

print

(

f

"0.2 actual value: {b}"

)

print

(

f

"0.3 actual value: {c}"

)

print

(

f

"0.1 + 0.2  = {a + b}"

)

print

(

f

"0.1 + 0.2 == 0.3 ? {0.1 + 0.2 == 0.3}"

)

=============================================

Demo 3: large numbers "swallowing" small ones

=============================================

print

(

"\n"

"="

60

)

print

(

"Demo 3: a small number swallowed when added to a large one"

)

print

(

"="

60

)

big

=

16777216.0

small

=

1.0

result

=

big + small

print

(

f

"{big} + {small} = {result}"

)

print

(

f

"Result equals the original? {result == big}"

)

Show that this number reaches the precision limit of float32

print

(

f

"\nReason: {big} needs {len(format(struct.unpack('>I', struct.pack('>f', big))[0], '032b')[:23])} mantissa bits in float32"

)

print

(

f

"The minimum gap between two adjacent float32 values is about 2^24 / 2^23 = 2.0"

)

=============================================

Demo 4: correct case-conversion technique

=============================================

print

(

"\n"

"="

60

)

print

(

"Demo 4: RUNOOB case - correct handling of money"

)

print

(

"="

60

)

from

decimal

import

Decimal

Wrong approach: use floating point

float_total

=

0.1

0.2

print

(

f

"Wrong (floating point): 0.1 + 0.2 = {float_total}"

)

Right approach: use Decimal

decimal_total

=

Decimal

(

'0.1'

)

(

'0.2'

)

print

(

f

"Correct (Decimal): Decimal('0.1') + Decimal('0.2') = {decimal_total}"

)

Or use integers (in units of cents)

cents_total

=

10

20

 

0.1 yuan = 10 cents, 0.2 yuan = 20 cents

print

(

f

"Correct (integer cents): 10 cents + 20 cents = {cents_total} cents = {cents_total/100} yuan"

)

=============================================

Demo 5: special values of floating point

=============================================

print

(

"\n"

"="

60

)

print

(

"Demo 5: special values of floating point"

)

print

(

"="

60

)

import

math

Infinity

print

(

f

"float('inf')    = {float('inf')}"

)

print

(

f

"1.0 / 0.0       = {1.0 / 0.0}"

)

print

(

f

"float('inf') > 1e1000000 = {float('inf') > 1e1000000}"

)

NaN

print

(

f

"float('nan')     = {float('nan')}"

)

print

(

f

"0.0 / 0.0        = {0.0 / 0.0}"

)

print

(

f

"float('nan') == float('nan') ? {float('nan') == float('nan')}"

)

print

(

f

" (NaN is not equal to any value, including itself!)"

)

Check NaN

print

(

f

"math.isnan(float('nan')) = {math.isnan(float('nan'))}"

)


Practical advice: what to use when

Scenario Recommended type Reason
Scientific computing, graphics rendering float or double Sufficient precision, well supported by hardware acceleration
Financial/monetary calculations Decimal / BigDecimal Exact decimal arithmetic, no rounding error
Counters, indices int / long Exact integers, no precision issues
Comparing floats Compare with a tolerance Should not use == directly; use abs(a-b) < epsilon
Currency storage/transmission Integers (in units of cents) Avoid floating-point errors during serialization