Understanding Floating-Point Arithmetic
Introduction to Numbers
Beyond Whole Numbers
We use numbers to describe the world, from counting apples to measuring the distance between stars. The simplest numbers we learn are integers. These are the whole numbers you can count on your fingers, their negative counterparts, and zero.
Integers: ..., -3, -2, -1, 0, 1, 2, 3, ...
Computers are great at working with integers. They can add, subtract, and multiply them with perfect precision. But what happens when you divide? Sometimes it works out cleanly, like . But often, it doesn't. What is ?
The Gaps on the Number Line
If we only had integers, we couldn't answer properly. We'd be stuck with a remainder. Many programming languages, when performing integer division, will simply throw away the part after the decimal point. They truncate the result.
// In many programming languages like C++ or Java
int result = 5 / 2;
// The value of 'result' is 2, not 2.5
This is a problem. The world isn't made of just whole things. We need to measure half a cup of flour, calculate a price of $2.50, or track a company's growth of 3.7%. We need to fill in the gaps between the integers on the number line.
This is where the concept of real numbers comes in. Real numbers include all the integers, plus all the fractions and decimals in between. They form a continuous, unbroken line.
The Two Kinds of Real Numbers
Real numbers can be split into two main groups: rational and irrational.
Rational numbers are any numbers that can be written as a fraction, or ratio, of two integers. This includes simple fractions like (or 0.5), repeating decimals like (or 0.333...), and even integers themselves, since any integer can be written as a fraction over 1 (for example, ).
Irrational numbers cannot be expressed as a simple fraction. Their decimal representations go on forever without ever repeating a pattern. Famous examples include (the ratio of a circle's circumference to its diameter) and (the square root of 2).
Most calculations in science, engineering, and finance rely on real numbers. From calculating the trajectory of a spacecraft to modeling stock market fluctuations, integers alone are not enough. We need a way for computers to handle this much richer, more complex world of numbers.
Representing the infinite, continuous nature of real numbers inside a computer with finite memory is a significant challenge. How can you store a number like that goes on forever? You can't. You have to approximate it. This fundamental problem leads to the systems computers use to work with real numbers, which we'll explore next.
What is the primary limitation of using only integers for calculations, especially in programming?
Which of the following numbers is irrational?
