Skip to main content

Floating-point

Overview

A Floating-point data type represents real numbers, especially those with fractional parts. It’s called “floating” because the decimal point can move, allowing very large and very small numbers to share the same format.

Floating-point numbers are the workhorses behind science, graphics, finance, and simulations.


How Floating-point Numbers Are Stored

Most systems follow the IEEE 754 standard.

A floating-point number is stored as three parts:

Sign: positive or negative Exponent: scales the number Mantissa (Significand): holds the precision

Conceptually:

value = sign × mantissa × base^exponent

This design trades exactness for range.

Common Floating-point Types

TypeTypical SizePrecision
float32-bit~7 decimal digits
double64-bit~15 decimal digits
long double≥ 80-bitplatform dependent

Key Characteristics

Supports fractions and decimals Limited precision Rounding errors are expected, not bugs

Example surprise:

0.1 + 0.2 ≠ 0.3

This happens because some decimals cannot be represented exactly in binary.


Common Operations

OperationExample
Arithmetic3.14 * 2.0
Comparisona < b
Roundinground(2.7)
Trigonometrysin(x), cos(x)

Example

Pseudocode

pi = 3.14159
radius = 5.0
area = pi \* radius \* radius

Real-world analogy

Floating-point numbers are like measuring cups with markings. Great for estimation, dangerous for precision chemistry ⚗️.


Time and Space Complexity

  • Space: O(1)
  • Operations: O(1) (hardware-supported)

Use Cases

  • Scientific calculations
  • Game physics
  • Machine learning
  • Computer graphics
  • Statistical analysis

Advantages

  • Handles very large and very small numbers
  • Fast arithmetic on modern CPUs
  • Standardized across platforms

Limitations

  • Precision errors
  • Unsafe for exact financial calculations
  • Equality comparisons can be unreliable

Best Practices

  • Avoid direct equality checks
  • Use tolerance-based comparisons
  • Prefer fixed-point or decimal types for money