Programming fundamentalsLesson 3 of 6 in the course Expressions

Binary Floating-Point Approximation, Overflow, and Rounding

5 flashcards · 5 quiz questions · 5 match pairs · 4 fill-in sentences · English

Lesson progress
0 / 5

Your progress is kept in this browser only.Sign up to save it

Summary

Computers store information in binary, a system that uses only the digits 0 and 1. For example, the whole number 55 is represented in binary as 101.

Python stores floating-point values using a binary representation. Some decimal fractions do not have an exact, finite binary representation. When such a value is stored, the computer uses the closest representable value instead. This is why a floating-point value may be an approximation of the decimal value written in the program.

All flashcards

Why are some floating-point values approximations?
Python represents floating-point values using binary. Some decimal fractions, including 0.10.1, do not have an exact finite binary representation, so the computer stores the nearest representable value.
What is a round-off error?
It is the difference between a true value and the approximation used for that value in storage or computation. It can appear in calculated or displayed floating-point results.
What is an overflow error?
An overflow error occurs when a floating-point result is too large to fit within the representable range. For example, `3.0**1024` can exceed that range.
How does Python's `round()` function work?
`round(number, places)` rounds a number to the specified number of decimal places. If `places` is omitted, it rounds to the nearest integer.
How can rounding help when calculating a tip?
Multiply the bill by the tip ratio, then use a suitable precision such as `round(tip, 2)` for a two-decimal displayed amount. This gives a practical presentation, though it does not make floating-point storage exact.

Quiz questions

  1. Why can a decimal value such as 0.10.1 be stored only approximately as a floating-point number?Answer: Because 0.10.1 has no exact finite representation in binary floating point.
  2. What is a round-off error?Answer: The difference between a true value and the approximation used to represent or calculate it.
  3. Which situation is most likely to cause an overflow error?Answer: Calculating a floating-point result that is larger than the maximum value the system can represent.
  4. What does `round(2.451, 2)` return?Answer: 2.45
  5. A program calculates a tip and displays an unexpectedly long decimal representation. Which response best addresses the display precision?Answer: Use `round(tip, 2)` to display two decimal places, while recognizing that the stored value may still be approximate.

Based on Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield, Narges Norouzi (OpenStax), licensed CC BY 4.0. Adapted into a summary, flashcards and quizzes.

All Programming fundamentals lessons