Floating Point Numbers (Floats)
A Float (Floating Point Number) is a data type used in computer programming to represent real numbers that have a fractional part (decimals).
1. The Core Concept
Computers store numbers in binary (0s and 1s).
- Integers: Store whole numbers exactly (e.g.,
5,100,-42). - Floats: Store numbers using a formula similar to scientific notation ($m \times 2^e$). This allows them to represent a massive range of values, from extremely small ($1.5 \times 10^{-45}$) to extremely large ($3.4 \times 10^{38}$), by "floating" the decimal point.
2. IEEE 754 Standard
Most modern computers follow the IEEE 754 standard for representing floating-point numbers. A float is stored in three parts:
- Sign Bit: Positive or Negative.
- Exponent: Determines the magnitude (where the decimal point sits).
- Mantissa (Significand): The actual digits of the number.
Types of Precision
- Single Precision (Float): Uses 32 bits. Accurate to about 7 decimal digits.
- Double Precision (Double): Uses 64 bits. Accurate to about 15 decimal digits. (This is the default number type in JavaScript and Python).
3. The Precision Problem
Because computers use base-2 (binary) and humans use base-10 (decimal), some numbers cannot be represented exactly. Just like $1/3$ in decimal is $0.3333...$ (repeating), $0.1$ in binary is an infinitely repeating fraction.
This leads to the infamous rounding error:
// JavaScript / Python
console.log(0.1 + 0.2);
// Output: 0.30000000000000004
Rule of Thumb: Never use floats for financial calculations (money). Use Integers (cents) or a Decimal type instead.
4. Comparing Floats
Because of precision issues, you should never compare floats using ==.
- Bad:
if (a == b) - Good: Check if the difference is smaller than a tiny number (Epsilon).
a = 0.1 + 0.2
b = 0.3
epsilon = 0.00001
if abs(a - b) < epsilon:
print("They are equal")
5. Special Values
Floats can represent special non-number states:
- Infinity (
inf): Result of dividing a positive number by zero. - NaN (Not a Number): Result of invalid operations like
0 / 0orsqrt(-1).