Skip to content

Data

AP Computer Science PrinciplesTopic 2

Video lesson for this topic Open the video page
8:13

Data

Play a song. What reaches your ear is a wave — smooth, continuous, never jumping from one value to the next. But your phone cannot store a wave. It can only…

English narration · English and 中文 subtitles you can switch

2.1

Binary Numbers

Syllabus
Enduring UnderstandingLearning ObjectiveEssential Knowledge

DAT-1
The way a computer represents data internally is different from the way the data are interpreted and displayed for the user. Programs are used to translate data into a representation more easily understood by people.

DAT-1.A
Explain how data can be represented using bits. [Skill 3.C]

  • DAT-1.A.1 Data values can be stored in variables, lists of items, or standalone constants and can be passed as input to (or output from) procedures.
  • DAT-1.A.2 Computing devices represent data digitally, meaning that the lowest-level components of any value are bits.
  • DAT-1.A.3 Bit is shorthand for binary digit and is either 0 or 1.
  • DAT-1.A.4 A byte is 8 bits.
  • DAT-1.A.5 Abstraction is the process of reducing complexity by focusing on the main idea. By hiding details irrelevant to the question at hand and bringing together related and useful details, abstraction reduces complexity and allows one to focus on the idea.
  • DAT-1.A.6 Bits are grouped to represent abstractions. These abstractions include, but are not limited to, numbers, characters, and color.
  • DAT-1.A.7 The same sequence of bits may represent different types of data in different contexts.
  • DAT-1.A.8 Analog data have values that change smoothly, rather than in discrete intervals, over time. Some examples of analog data include pitch and volume of music, colors of a painting, or position of a sprinter during a race.
  • DAT-1.A.9 The use of digital data to approximate real-world analog data is an example of abstraction.
  • DAT-1.A.10 Analog data can be closely approximated digitally using a sampling technique, which means measuring values of the analog signal at regular intervals called samples. The samples are measured to figure out the exact bits required to store each sample.

DAT-1.B
Explain the consequences of using bits to represent data. [Skill 1.D]

  • DAT-1.B.1 In many programming languages, integers are represented by a fixed number of bits, which limits the range of integer values and mathematical operations on those values. This limitation can result in overflow or other errors.
  • DAT-1.B.2 Other programming languages provide an abstraction through which the size of representable integers is limited only by the size of the computer's memory; this is the case for the language defined in the exam reference sheet.
  • DAT-1.B.3 In programming languages, the fixed number of bits used to represent real numbers limits the range and mathematical operations on these values; this limitation can result in round-off and other errors. Some real numbers are represented as approximations in computer storage.
    • Exclusion statement: Specific range limitations for real numbers are outside the scope of this course and the AP Exam.

DAT-1.C
For binary numbers:
a. Calculate the binary (base 2) equivalent of a positive integer (base 10) and vice versa. [Skill 2.B]
b. Compare and order binary numbers. [Skill 2.B]

  • DAT-1.C.1 Number bases, including binary and decimal, are used to represent data.
  • DAT-1.C.2 Binary (base 2) uses only combinations of the digits zero and one.
  • DAT-1.C.3 Decimal (base 10) uses only combinations of the digits $0 - 9$.
  • DAT-1.C.4 As with decimal, a digit's position in the binary sequence determines its numeric value. The numeric value is equal to the bit's value (0 or 1) multiplied by the place value of its position.
  • DAT-1.C.5 The place value of each position is determined by the base raised to the power of the position. Positions are numbered starting at the rightmost position with 0 and increasing by 1 for each subsequent position to the left.

Source: College Board AP Course and Exam Description

Binary digits on a display — all digital data is ultimately stored as 0s and 1s
Binary digits on a display — all digital data is ultimately stored as 0s and 1s

On 4 June 1996 the first Ariane 5 rocket was destroyed about 37 seconds after launch. Its guidance software tried to put a large number, stored in 64 bits, into a space of only 16 bits. The number did not fit, the guidance system failed, and years of work ended in the sky. The way a computer stores a value has limits, and those limits have real results. This unit explains how data become bits, and how bits become knowledge.

Computers store everything as bits 位 – each a 0 or 1. A group of 8 bits is a byte 字节. Numbers are stored in binary 二进制 (base 2), where each place is a power of two ($1, 2, 4, 8, 16, \dots$) instead of the powers of ten in decimal 十进制. For example, binary 1011 is $8+2+1=11$.

The rule behind this: number the positions from the right, starting at 0. Each bit is worth its value (0 or 1) times $2^{\text{position}}$. Decimal works the same way with powers of 10.

An 8-bit place-value chart: the 1s sit under the values that add to the number
An 8-bit place-value chart: the 1s sit under the values that add to the number

Worked example. To convert binary 1101 to decimal, write the place values 8 4 2 1 under the bits 1 1 0 1 and add the ones that have a 1: $8+4+0+1=13$. Going the other way, convert 19 to binary by subtracting the largest power of two that fits: $19-16=3$, then $3-2=1$, then $1-1=0$, so the bits sit at the 16, 2, and 1 places $\rightarrow$ 10011 (check: $16+2+1=19$).

Worked example (compare and order). Put these in order, smallest first: binary 1100, decimal 11, binary 1010.

Change them all to decimal: 1100 is $8+4=12$ and 1010 is $8+2=10$. The order is 1010 (10), decimal 11, 1100 (12). For two binary numbers of the same length there is a quicker way: read from the left, and at the first place they differ, the one with the 1 is larger.

Because a computer has a finite number of bits, it can represent only a limited range of values. This causes two effects tested on the exam:

  • Overflow error 溢出错误: a number too large for the available bits cannot be stored correctly.
  • Round-off (rounding) error 舍入错误: many numbers with decimals (real numbers), such as 0.1, can only be approximated, because infinitely many real values must map onto finitely many bit patterns.

On the exam, the AP pseudocode has no fixed size for integers: they are limited only by the computer's memory. So expect overflow only when a question states a fixed number of bits. Round-off is easy to see in many real languages, where 0.1 + 0.2 gives 0.30000000000000004.

Worked example (how many bits?). With $n$ bits there are $2^n$ different patterns; each extra bit doubles the count.

Question Working Answer
Largest whole number in 4 bits 1111 is $8+4+2+1$ 15
Patterns in 3 bits $2^3$ 8
Bits to give 100 students different IDs $2^6 = 64$ is too few; $2^7 = 128$ 7 bits
Patterns gained from 6 bits to 7 bits $128 - 64$ 64 more, twice as many

In a 4-bit system, $15 + 1$ needs 10000, five bits; with only four, the result cannot be stored: an overflow error.

All data – text, images, sound – is ultimately encoded as binary. An image is a grid of pixels 像素, each stored as numbers for its colors; sound is stored as numbers sampled many times per second.

Bits as abstraction

Abstraction 抽象 means reducing complexity by keeping the main idea and hiding details that do not matter for the question. When you see the letter A on a screen, you do not need to think about bits. Bits are grouped to stand for bigger ideas such as numbers, characters and colors, and the same bits can mean different things in different contexts:

The byte 01000001 read as the number 65, the character A, and a dark red colour level
The bits do not say what they mean; the program that reads them decides

Analog and digital

Analog 模拟 data change smoothly, with no steps: the pitch of a song, the colors of a painting, the position of a runner. Digital 数字 data are stored as separate values. To store analog data, a device takes samples 采样: it measures the signal at regular intervals and stores each measurement as bits.

A smooth curve measured at regular intervals; each measurement is rounded to a whole number and stored, giving a stepped line close to the curve
Sampling: discrete measurements approximate the original signal

The result is an approximation, so digital data of this kind are themselves an abstraction. More samples per second, and more bits for each sample, give a closer match, and a larger file.

Worked example (the size of sound). One minute of mono sound is sampled 44,100 times per second, with 16 bits per sample. Ignoring headers and compression, how large is the file?

  1. Samples: $44100 \times 60 = 2646000$.
  2. Bits: $2646000 \times 16 = 42336000$.
  3. Bytes: $42336000 \div 8 = 5292000$, about 5.3 million bytes.

This is why sound and video are so often compressed.

Explore

Convert between binary and decimal

Computers store numbers in binary (base 2). Each bit is a power of two; add the place values of the 1-bits to read the decimal number.

Vocabulary Train
English
bits/bɪts/
byte/baɪt/
binary/ˈbaɪnəri/
decimal/ˈdesɪml/
Overflow error/ˌəʊvəˈfləʊ ˈerə/
Round-off (rounding) error/raʊnd ɒf ˈerə/
pixels/ˈpɪkslz/
abstraction/əbˈstrækʃn/
analog/ˈænəlɒɡ/
digital/ˈdɪdʒɪtl/
sample/ˈsæmpl/
Watch lesson
2.2

Data Compression

Syllabus
Enduring UnderstandingLearning ObjectiveEssential Knowledge

DAT-1
The way a computer represents data internally is different from the way the data are interpreted and displayed for the user. Programs are used to translate data into a representation more easily understood by people.

DAT-1.D
Compare data compression algorithms to determine which is best in a particular context. [Skill 1.D]

  • DAT-1.D.1 Data compression can reduce the size (number of bits) of transmitted or stored data.
  • DAT-1.D.2 Fewer bits does not necessarily mean less information.
  • DAT-1.D.3 The amount of size reduction from compression depends on both the amount of redundancy in the original data representation and the compression algorithm applied.
  • DAT-1.D.4 Lossless data compression algorithms can usually reduce the number of bits stored or transmitted while guaranteeing complete reconstruction of the original data.
  • DAT-1.D.5 Lossy data compression algorithms can significantly reduce the number of bits stored or transmitted but only allow reconstruction of an approximation of the original data.
  • DAT-1.D.6 Lossy data compression algorithms can usually reduce the number of bits stored or transmitted more than lossless compression algorithms.
  • DAT-1.D.7 In situations where quality or ability to reconstruct the original is maximally important, lossless compression algorithms are typically chosen.
  • DAT-1.D.8 In situations where minimizing data size or transmission time is maximally important, lossy compression algorithms are typically chosen.

Source: College Board AP Course and Exam Description

Hard-disk platters and head: data compressed and stored as magnetic patterns
Hard-disk platters and head: data compressed and stored as magnetic patterns

Compression 压缩 reduces the number of bits needed to store or send data. Two kinds:

  • Lossless compression 无损压缩 lets you restore the exact original data (used for text and programs, where every bit matters).
  • Lossy compression 有损压缩 throws away some data to shrink the size further (used for photos, music, video, where a small quality loss is acceptable).
Compression methods: lossless versus lossy, with common examples
Compression methods: lossless versus lossy, with common examples

Choosing between them trades size against fidelity: lossless keeps everything but saves less; lossy saves more but loses detail permanently. Prefer lossless when the data must be exact.

Situation Choice Reason
Sending a program file lossless one wrong bit can stop it working
Storing a medical scan lossless quality matters most
A live video call on a slow link lossy transmission time matters most
A website with thousands of photos lossy a small file matters more than perfect detail

Questions of this kind ask which is most important in the situation: exact reconstruction, or size and speed.

Worked example (run-length encoding). A row of image pixels reads WWWWWWBBBWWWW, 13 symbols. Run-length encoding 游程编码 stores each run as a count and a symbol: 6W3B4W, 6 symbols. Decoding gives back exactly WWWWWWBBBWWWW, so this is lossless. It saves space only when the data has long runs: WBWBWB becomes 1W1B1W1B1W1B, twice as long. No lossless method can shrink every possible input.

How much a file shrinks depends on two things: how much redundancy 冗余 (repeated or predictable content) it has, and which algorithm is used. Notice also that fewer bits does not always mean less information: 6W3B4W holds everything that the 13-symbol row held.

Explore

Compress a run of repeats

Run-length encoding is a lossless compression: a long run of the same symbol is replaced by the symbol and a count, shrinking the data with no information lost.

Vocabulary Train
English
Compression/kəmˈpreʃn/
Lossless compression/ˈlɒsləs kəmˈpreʃn/
Lossy compression/ˈlɒsi kəmˈpreʃn/
run-length encoding/rʌn leŋθ enˈkəʊdɪŋ/
redundancy/rɪˈdʌndənsi/
Watch lesson
2.3

Extracting Information from Data

Syllabus
Enduring UnderstandingLearning ObjectiveEssential Knowledge

DAT-2
Programs can be used to process data, which allows users to discover information and create new knowledge.

DAT-2.A
Describe what information can be extracted from data. [Skill 5.B]

  • DAT-2.A.1 Information is the collection of facts and patterns extracted from data.
  • DAT-2.A.2 Data provide opportunities for identifying trends, making connections, and addressing problems.
  • DAT-2.A.3 Digitally processed data may show correlation between variables. A correlation found in data does not necessarily indicate that a causal relationship exists. Additional research is needed to understand the exact nature of the relationship.
  • DAT-2.A.4 Often, a single source does not contain the data needed to draw a conclusion. It may be necessary to combine data from a variety of sources to formulate a conclusion.

DAT-2.B
Describe what information can be extracted from metadata. [Skill 5.B]

  • DAT-2.B.1 Metadata are data about data. For example, the piece of data may be an image, while the metadata may include the date of creation or the file size of the image.
  • DAT-2.B.2 Changes and deletions made to metadata do not change the primary data.
  • DAT-2.B.3 Metadata are used for finding, organizing, and managing information.
  • DAT-2.B.4 Metadata can increase the effective use of data or data sets by providing additional information.
  • DAT-2.B.5 Metadata allow data to be structured and organized.

DAT-2.C
Identify the challenges associated with processing data. [Skill 5.D]

  • DAT-2.C.1 The ability to process data depends on the capabilities of the users and their tools.
  • DAT-2.C.2 Data sets pose challenges regardless of size, such as:
    • the need to clean data
    • incomplete data
    • invalid data
    • the need to combine data sources
  • DAT-2.C.3 Depending on how data were collected, they may not be uniform. For example, if users enter data into an open field, the way they choose to abbreviate, spell, or capitalize something may vary from user to user.
  • DAT-2.C.4 Cleaning data is a process that makes the data uniform without changing their meaning (e.g., replacing all equivalent abbreviations, spellings, and capitalizations with the same word).
  • DAT-2.C.5 Problems of bias are often created by the type or source of data being collected. Bias is not eliminated by simply collecting more data.
  • DAT-2.C.6 The size of a data set affects the amount of information that can be extracted from it.
  • DAT-2.C.7 Large data sets are difficult to process using a single computer and may require parallel systems.
  • DAT-2.C.8 Scalability of systems is an important consideration when working with data sets, as the computational capacity of a system affects how data sets can be processed and stored.

Source: College Board AP Course and Exam Description

Data 数据 becomes useful when we extract information 信息 from it – patterns, trends, and answers to questions. Large data sets can reveal correlations a small one cannot, but data must be cleaned (fixing errors and inconsistencies) and often transformed or filtered first. A correlation 相关性 between two things does not prove that one causes the other – a key caution. Metadata 元数据 (data about data, like a photo's date and location) helps organize and search large collections.

Often one source is not enough to reach a conclusion, and data from several sources must be combined.

Worked example (what metadata can tell you). A phone photo has this metadata: date, time, location, file size, camera model.

Question From the metadata alone?
Where and when was it taken? Yes
How much storage does it use? Yes
Who is in the photo? No: that is in the data, the picture itself
Is the sky blue in the photo? No: same reason

Editing descriptive metadata such as the date or camera model need not change the image pixels. Metadata are data about other data and may be stored inside the same file. Some metadata, such as orientation, can affect how the picture is displayed.

Worked example (correlation is not cause). A city's data shows that on days with more ice-cream sales, more people are treated for sunburn. Ice cream does not cause sunburn: both rise on hot, sunny days. The heat is a third factor behind both. To claim a cause you need more than a pattern in the data, such as an experiment that changes one thing and keeps the rest the same.

Why data are hard to work with

Data sets of every size bring the same problems:

Problem Example What to do
Not uniform NYC, New York and new york in one column clean them: one spelling, same meaning
Incomplete the age column is blank in some rows find the data, or leave those rows out and say so
Invalid age is 250 check that values are possible
Separate sources one file lists names, another lists ID numbers find a way to match the rows

Cleaning data 数据清洗 makes data uniform without changing their meaning. It would be wrong to "clean" a real low score up to the average.

More data does not remove bias. A city puts an online survey on its website to ask whether homes have good Internet. People without Internet cannot answer. Doubling the number of replies still leaves them out: the problem is how the data were collected, not how much there is.

Very large data sets may also need more than one computer, so scalability 可扩展性 matters: what a system can do with data depends on its computing power and storage.

Filter the rows you need, then count, sum or average them
Filter the rows you need, then count, sum or average them
Vocabulary Train
English
Data/ˈdeɪtə/
information/ˌɪnfəˈmeɪʃn/
correlation/ˌkɒrɪˈleɪʃn/
Metadata/ˌmetəˈdeɪtə/
cleaning data/ˈkliːnɪŋ ˈdeɪtə/
scalability/ˌskeɪləˈbɪlɪti/
2.4

Using Programs with Data

Syllabus
Enduring UnderstandingLearning ObjectiveEssential Knowledge

DAT-2
Programs can be used to process data, which allows users to discover information and create new knowledge.

DAT-2.D
Extract information from data using a program. [Skill 2.B]

  • DAT-2.D.1 Programs can be used to process data to acquire information.
  • DAT-2.D.2 Tables, diagrams, text, and other visual tools can be used to communicate insight and knowledge gained from data.
  • DAT-2.D.3 Search tools are useful for efficiently finding information.
  • DAT-2.D.4 Data filtering systems are important tools for finding information and recognizing patterns in data.
  • DAT-2.D.5 Programs such as spreadsheets help efficiently organize and find trends in information.
  • DAT-2.D.6 Some processes that can be used to extract or modify information from data include the following:
    • transforming every element of a data set, such as doubling every element in a list, or adding a parent's email to every student record
    • filtering a data set, such as keeping only the positive numbers from a list, or keeping only students who signed up for band from a record of all the students
    • combining or comparing data in some way, such as adding up a list of numbers, or finding the student who has the highest GPA
    • visualizing a data set through a chart, graph, or other visual representation

DAT-2.E
Explain how programs can be used to gain insight and knowledge from data. [Skill 5.B]

  • DAT-2.E.1 Programs are used in an iterative and interactive way when processing information to allow users to gain insight and knowledge about data.
  • DAT-2.E.2 Programmers can use programs to filter and clean digital data, thereby gaining insight and knowledge.
  • DAT-2.E.3 Combining data sources, clustering data, and classifying data are parts of the process of using programs to gain insight and knowledge from data.
  • DAT-2.E.4 Insight and knowledge can be obtained from translating and transforming digitally represented information.
  • DAT-2.E.5 Patterns can emerge when data are transformed using programs.

Source: College Board AP Course and Exam Description

Programs process data at scales humans cannot. Common operations are filtering 过滤 (keeping only rows that meet a condition), cleaning (removing errors), and visualizing 可视化 (charts and graphs that make patterns visible). Combining data from multiple sources can reveal more, but raises privacy 隐私 concerns. Interactive tools and visualizations let people explore data and draw their own conclusions.

Most data work is built from four actions:

Action Example
Transform every element double each number in a list; add a parent's email to each student record
Filter keep only positive numbers; keep only students in the band
Combine or compare add up a list; find the highest GPA
Visualize draw a chart of the results

Worked example (filter, then combine). What does this display if numbers is [3, -1, 4, -5]?

total ← 0
FOR EACH n IN numbers
{
   IF (n > 0)
   {
      total ← total + n
   }
}
DISPLAY(total)

The IF filters out -1 and -5; adding combines the rest. It displays $3+4=7$.

This work is iterative: a chart suggests a pattern, the pattern suggests a new question, and the program is changed to ask it. Programs can also group similar rows without being told the groups, called clustering 聚类, or put each row into a known category, called classifying 分类. Search tools and spreadsheets are everyday versions of the same ideas.

Worked example (what can the data answer?). A school stores one row per student:

Name Grade Transport Distance (km)
Ana 10 bus 6.5
Ben 11 bike 2.0
Chen 10 bus 8.0
  1. “What is the mean distance for students who come by bus?” Can be answered: filter Transport = bus, then average Distance: $\frac{6.5 + 8.0}{2} = 7.25$ km.
  2. “How many grade 10 students cycle?” Can be answered: filter on two columns, then count: 0.
  3. “Why do students choose the bus?” Cannot: no column records reasons.
  4. “How long is each journey in minutes?” Cannot: time is not stored, and distance alone does not give it.

Exam questions of this kind turn on one check: is every piece of information the question needs in a column?

Exam skill: be able to explain how a program helps find information in a large data set, and why correlation shown in the data does not establish causation.

Cleaning data makes entries consistent before a program processes them
Cleaning data makes entries consistent before a program processes them
Vocabulary Train
English
filtering/ˈfɪltərɪŋ/
visualizing/ˈvɪʒuːəlaɪzɪŋ/
privacy/ˈprɪvəsi/
clustering/ˈklʌstərɪŋ/
classifying/ˈklæsɪfaɪɪŋ/
2.4

Practice

Answer each before reading the answers below.

  1. Convert the binary number $10110110$ to decimal, and the decimal number $45$ to binary.
  2. How many different values can $6$ bits represent? How many bits are needed to give $200$ students each a unique ID?
  3. Should a text document be compressed with lossless or lossy compression? What about streaming video? Explain.
  4. A $4$-bit unsigned variable holds $15$, and $1$ is added. What happens?
  5. Run-length encode AAAABBBCCD. Is the result shorter?
  6. Give two examples of metadata stored with a digital photograph, and one privacy risk.
  7. Data show that ice-cream sales and drownings rise together. Can we conclude that ice cream causes drowning? Explain.
2.4

Answers

  1. $128 + 32 + 16 + 4 + 2 = 182$; $45 = 32 + 8 + 4 + 1 = 101101_2$.
  2. $2^6 = 64$. $2^7 = 128 < 200 \le 256 = 2^8$, so $8$ bits.
  3. Text: lossless, because every character must be restored exactly. Video: lossy is acceptable, because small losses are hard to notice and the file becomes much smaller.
  4. An overflow error: $16$ needs $5$ bits, so the result cannot be stored (it may wrap around to $0$).
  5. 4A3B2C1D: $8$ characters instead of $10$, so it is shorter.
  6. Date and time taken, camera model, GPS location. The location can reveal where someone lives.
  7. No. Correlation does not show causation; a third variable (hot weather) increases both.
2.4

Exam tips

  • Convert confidently between binary and decimal, and order numbers given in both.
  • Remember a bit is one binary digit and a byte is 8 bits; $n$ bits represent $2^n$ values.
  • Explain that all data — numbers, text, images, sound — is stored as binary, and that finite bits cause overflow and round-off.
  • Distinguish lossless from lossy compression and when each is appropriate.
  • Show the analog-to-digital idea: sampling turns a continuous signal into discrete values.
  • Before you answer a "can the data show this?" question, check that every fact needed is in a column or in the metadata.

Interactive lessons on this topic

Work through it step by step, with instant-check exercises.

Past Papers

More topics in AP Computer Science Principles

Log in or create account

IGCSE, A-Level & AP