2016 September 12,

CS 111: Integers vs. Floating-Point Numbers

Try the following lines of code, in order.

x = 1.0 / 3.0

x

(x ** 0.1) ** 10

(x ** 0.01) ** 100

(x ** 0.001) ** 1000

(x ** 0.0001) ** 10000

Each of these commands (except the first) should return 0.333..., because the powers undo each other. But we get imprecise answers, that drift farther and farther away from 0.333.... Why? The computer stores these numbers in a format called floating point, which has a limited number of decimal places. So the value stored in x is not exactly equal to 1 / 3. As we do more and more extreme arithmetic with x, the slight discrepancy between x and 1 / 3 gets amplified.

Such precision problems are unavoidable when working with floating-point numbers. But, as we shall see later, there are times when we want arithmetic in our programs to behave exactly correctly. For this reason, Python (like most other programming languages) maintains a second kind of arithmetic: integer-only. (An integer is a whole number — positive, negative, or zero.)

Let's try some arithmetic with integers.

8 + 4

8 - 4

8 * 4

8 / 4

8 ** 4

Question 03A: Why, do you think, does the division operation act that way?

If you want to force division to produce an integer, then you need to use the // operator.

8 // 4

But this leads to another question: What if the quotient of the two integers is not an integer?

8 // 4

9 // 4

10 // 4

11 // 4

12 // 4

13 // 4

As you can see, the // reports the integer part of the quotient, throwing away the remainder. If you want to get the remainder, then use the % operator.

8 % 4

9 % 4

10 % 4

11 % 4

12 % 4

13 % 4

You can also mix integers and floating-point numbers.

8 + 4

8 + 4.0

8.0 + 4

8.0 + 4.0

Question 03B: What is the simple rule for determining whether the output of mixed arithmetic like this is integer or floating-point?