Back

Activity 2.16: The Limits of Bits

divider

Activity 2.16

The Limits of Bits

Key Concepts

Overflow

Round-Off

Analog Data and Sampling

Digital Data Is an Abstraction

A Byte Has Nowhere to Put 256

Activity 2.14's byte had eight places, worth 128 down to 1. A ninth place would be worth 256, and there is not one. Store 300 in eight bits and the 256 is simply dropped: 44 is left. No error. Just a believable, wrong number.

Today you find the same wall inside C#'s own numbers: in whole numbers, in decimals, and in anything from the real world that changes smoothly. Every one of them is stored in a fixed number of bits, and each runs into that limit in its own way.

An int Is 32 Bits

Every int you have ever declared is stored in 32 bits. Thirty-two bits can make about four billion patterns, and C# splits them between negative and positive numbers.

Value Trace
an int has 32 bits
smallest -2147483648
largest 2147483647

An int Is 32 Bits

So what is the largest int, plus one? Predict it before the output appears.

Demo
int big = 2147483647;
big = big + 1;
Console.WriteLine(big);
Demo
-2147483648

That Is an Overflow Error

The College Board's definition: an overflow error happens when a computer tries to handle a number outside the defined range of values.

The count does not stop at the top. It wraps around to the bottom of the range, the way a car's odometer rolls from 99999 to 00000. And C# does not stop the program or print a warning. The program carries on with the wrong number.

A Bigger Type Moves the Wall

Activity 2.12 met long: the same idea as int, with 64 bits instead of 32.

Value Trace
int 32 bits up to about 2 billion
long 64 bits up to about 9 quintillion
Activity 2.12: Doubling(64) -> 0

A Bigger Type Moves the Wall

A long holds numbers four billion times bigger. It still has a top. Doubling(64) needed 65 bits, and the answer came out as 0.

Choosing a type is choosing a range. The programmer has to know how big the numbers can get, because the computer will not tell them when they get too big.

Decimals Run Out a Different Way

Write one third as a decimal. You start 0.333… and the threes never stop. You write as many as you have room for, then stop, and what you wrote is slightly too small.

Value Trace
1/3 in base 10 0.3333333333... the 3s never stop
1/10 in base 2 0.0001100110011... the 0011s never stop

Decimals Run Out a Different Way

One tenth is that kind of number in base 2. A double keeps about sixteen digits of it and stops. Predict both lines.

Demo
Console.WriteLine(0.1 + 0.2);
Console.WriteLine(0.1 + 0.2 == 0.3);
Demo
0.30000000000000004
False

That Is a Round-Off Error

Some real numbers can only be stored as approximations. The tiny difference between the stored value and the true one is a round-off error.

Overflow is a problem of range: the number is too big to fit. Round-off is a problem of precision: the number fits, but not exactly.

So Never Test Calculated Decimals With ==

0.1 + 0.2 == 0.3 was False. Any == on decimals you calculated can fail the same way.

Two fixes. Check that the difference is tiny instead of zero. Or, where you can, count in whole numbers: whole numbers in an int are exact, so a program that stores money as whole cents never has this problem.

How large or small a double can get is not on the exam. That they are approximations is.

Some Data Has No Next Value

Analog data changes smoothly rather than in steps. The pitch and volume of music. The colors in a painting. A sprinter's position during a race.

Between any two moments in the race there is another moment, with its own position. There is always something in between, and bits come only in whole steps.

So You Measure It Often

Sampling means measuring an analog signal at regular intervals. Each measurement, a sample, is stored in a fixed number of bits. A song on your phone is thousands of samples a second.

So You Measure It Often

Value Trace
the real signal a smooth curve: there is always a value in between
3 samples | | | was it a curve? a zigzag? a line?
21 samples | | | | | | | | | | | the shape is plain to see

Sample too rarely and very different signals give the same numbers. Sample more often and the shape comes back, at the cost of more numbers to store.

A Recording Is Not the Sound

The College Board: using digital data to approximate real-world analog data is an example of abstraction.

Abstraction keeps the main idea and drops the detail. Samples keep the shape of the sound and drop everything between them. It is close enough, and it is never all of it.

Today's Objectives

  • Explaining overflow as a number outside the range its storage defines
  • Explaining why some real numbers are stored as approximations
  • Distinguishing analog data from digital data
  • Describing sampling, and judging when a sample rate is too low

Key Terms

Overflow error
An error that occurs when a computer tries to handle a number outside the defined range of values.
Round-off error
The error introduced when a real number is stored as an approximation.
Analog data
Data whose values change smoothly rather than in discrete intervals.
Sampling
Measuring the value of an analog signal at regular intervals.

'F' → Fullscreen

divider

Build

Three glitch reports have come in from the arcade, and you are on bug duty. A player's score went negative, the snack machine kept a dollar and gave nothing back, and the sound meter shows garbage. Each one is a limit of bits. Tasks 1 and 2 go in a program named 2-16-glitch-hunt; Task 3 is a second program, 2-16-sampling.

How to read the code blocks. Each task's code block shows your whole program, from line 1, as it should look when that task is finished.

The green lines marked with a + are the ones you add or change for that task — everything else is already in your file. Do not type the + sign.


Task 1: The Score That Went Negative

  • The arcade's jackpot round adds a bonus of five hundred million points each round. Write the program below, but before you run it, predict the score after round 5 and write it down.
  • Run it. The player did nothing wrong. Say exactly where the information was lost, using the deck's range of an int.
  • Fix it by changing one word on line 1, then run it again. Task 2's code block shows the fix.
2-16-glitch-hunt
int score = 0;
int bonus = 500000000;
for (int round = 1; round <= 6; round++)
{
score = score + bonus;
Console.WriteLine($"Round {round}: score {score}");
}

Task 2: The Snack Machine That Kept a Dollar

  • A snack costs $1.00. Add the snack machine below, which takes ten dimes, and run it. It shows $1.00 paid, then asks for more coins.
  • The display is hiding the bug. Delete the :F2 on line 17 so it prints exactly what paid holds, and run it again. Record what dimes 3, 8 and 10 show.
  • Is this a range problem, like Task 1, or a precision problem? Explain why the if on line 20 chose the else.
  • Fix the machine by counting in cents. Replace paid with an int called paidCents, add 10 for each dime, and compare with 100. Change the message to print cents. Then explain why whole numbers cannot have this problem.
2-16-glitch-hunt
long score = 0;
int bonus = 500000000;
for (int round = 1; round <= 6; round++)
{
score = score + bonus;
Console.WriteLine($"Round {round}: score {score}");
}
Console.WriteLine();
double paid = 0;
for (int coin = 1; coin <= 10; coin++)
{
paid = paid + 0.10;
Console.WriteLine($"Dime {coin}: paid ${paid:F2}");
}
if (paid >= 1.00)
{
Console.WriteLine("Here is your snack.");
}
else
{
Console.WriteLine("Please insert more coins.");
}

Task 3: The Sound Meter

  • Start the second program, 2-16-sampling. Wave plays the part of a microphone: give it a time in seconds and it returns the volume of a sound at that moment. It changes smoothly, so it is analog. Do not change it.
  • ShowSamples(step) measures the wave every step seconds from 0 to 40 and draws each sample as a bar of #, one for every 5 units of volume, then the number. Read the bars down the screen like a graph turned on its side.
  • Run it, then answer three questions. (a) The real sound rises, falls, and rises again, smoothly. At which rate can you first see that in the bars? (b) One sample every 20 seconds gives 50, 20, 90. Describe a completely different sound that would give those same three numbers. (c) More samples cost more storage. Why would a music app not sample a million times a second?
2-16-sampling
ShowSamples(20);
ShowSamples(5);
ShowSamples(2);
void ShowSamples(int step)
{
Console.WriteLine($"One sample every {step} seconds:");
for (int t = 0; t <= 40; t = t + step)
{
double level = Wave(t);
for (int k = 0; k < level / 5; k++)
{
Console.Write("#");
}
Console.WriteLine($" {level:F0}");
}
Console.WriteLine();
}
// Wave stands in for a microphone. Do not change it.
double Wave(int t)
{
return 50 + 40 * Math.Sin(t / 5.0);
}

Challenge (Optional): Close Enough

  • Back in the snack machine's double version, write bool CloseEnough(double a, double b) that returns true when a - b and b - a are both less than 0.000001. Use it so the machine gives the snack.
  • You had to choose how close is close enough. Say why there is no single right answer for every program.
divider

Same Idea, Exam Notation — and It Behaves Differently

Doubling 1 sixty-four times, in both languages.

C#
long big = 1;
for (int i = 0; i < 64; i++)
{
big = big * 2;
}
Console.WriteLine(big);
Exam Notation
big ← 1
REPEAT 64 TIMES
{
big ← big * 2
}
DISPLAY(big)

1. C# Prints 0. The Exam Prints the Real Answer.

The C# version overflows, as Doubling(64) did in Activity 2.12. The exam version displays 18446744073709551616, all twenty digits. The College Board says the exam's language stores integers in as much space as they need, limited only by the computer's memory.

This is one of the few places where the exam's language behaves differently from C#, not just looks different. An exam question about a very large number is asking for the arithmetic. It is not testing whether you know C#'s limits. A question about overflow will say the storage has a fixed number of bits.

2. REPEAT n TIMES Has No Counter

The C# loop needs i to count, even though the body never uses it. REPEAT 64 TIMES just repeats. When an exam loop does need to know which pass it is on, it keeps its own variable and adds 1 to it.

divider

Checkpoint

After the fix in Task 1, the score prints exactly this.

Task 1, Fixed
Round 1: score 500000000
Round 2: score 1000000000
Round 3: score 1500000000
Round 4: score 2000000000
Round 5: score 2500000000
Round 6: score 3000000000

And Task 3 prints exactly this.

Task 3
One sample every 20 seconds:
########## 50
#### 20
################## 90
One sample every 5 seconds:
########## 50
################# 84
################## 86
############ 56
#### 20
### 12
######## 39
################ 76
################## 90
One sample every 2 seconds:
########## 50
############## 66
################ 79
################## 87
################## 90
################## 86
################ 77
############# 63
########## 48
####### 32
#### 20
### 12
### 10
### 15
##### 25
######## 39
########### 55
############## 70
################# 82
################## 89
################## 90
  • You predicted round 5 before running Task 1, and fixed it with one word
  • You recorded what dimes 3, 8 and 10 really held
  • Your snack machine counts in cents and gives the snack
  • You answered Task 3's three questions
divider

Reflection

Answer the following questions before submitting your work.

  1. Overflow and round-off both come from having a fixed number of bits. Explain the difference between them in your own words.
  2. The snack machine's display said $1.00 while the machine disagreed. Why does a display that rounds make a bug harder to find?
  3. Every number in the 20-second samples was measured correctly. Explain how correct measurements can still be misleading.
divider

Submit

Submit four things to the dropbox:

  1. Your 2-16-glitch-hunt and 2-16-sampling program files.
  2. Your Task 1 prediction and explanation.
  3. The values of dimes 3, 8 and 10, your range-or-precision answer, and your Task 3 answers.
  4. Your three reflection answers.

Activity Complete