Warning: foreach() argument must be of type array|object, bool given in /var/www/html/web/app/themes/studypress-core-theme/template-parts/header/mobile-offcanvas.php on line 20

Consider the following simple program inspired by Chapter 1.4.3: a = 1/947.0*947 b = 1 if a != b: print ’Wrong result!’ Try to run this example! One should never compare two floating-point objects directly using \(==\) or \(!=\) because round-off errors quickly make two identical mathematical values different on a computer. A better result is to test if \(|a-b|\) is sufficiently small, i.e., if \(a\) and \(b\) are "close enough" to be considered equal. Modify the test according to this idea. Thereafter, read the documentation of the function float_eq from SciTools: scitools numpyutils .float_eq (see page 80 for how to bring up the documentation of a module or a function in a module). Use this function to check whether two real numbers are equal within a tolerance. Name of program file: compare_float.py. 0

Short Answer

Expert verified
Replace direct comparison with a tolerance check using absolute difference or `float_eq` from SciTools.

Step by step solution

01

Understand the Problem

The task involves floating-point arithmetic errors in computing and comparing two floating-point numbers. Here, you are experimenting with the precision of floating points in programming, especially showing how direct comparison might yield unexpected results due to rounding errors.
02

Analyze the Code

Examine the code snippet provided: ```python a = 1/947.0*947 b = 1 if a != b: print('Wrong result!') ``` This calculates two variables, `a` and `b`, and checks if they are not equal. Because of floating-point precision, `a` may not exactly equal `b`, prompting an incorrect message.
03

Modify the Comparison

We modify the comparison from a direct comparison using `!=` to a check involving the difference being sufficiently small. Replace the condition check with an absolute difference comparison: ```python if abs(a - b) > 1e-9: print('Wrong result!') ``` Here, `1e-9` is a small number representing the tolerance level for the difference.
04

Introduce SciTools' float_eq

Utilize the `float_eq` function provided by SciTools to check the equality of floating-point numbers within a tolerance. First, ensure you have SciTools installed. Then, you can use: ```python from scitools.numpyutils import float_eq if not float_eq(a, b, atol=1e-9): print('Wrong result!') ``` The `float_eq` function simplifies comparing two floating-point numbers within a specified absolute tolerance.
05

Save the Modified Program

Ensure your modified code is saved in a file named `compare_float.py`. The entire content should include importing `float_eq` and implementing it for comparing `a` and `b` with a small tolerance.

Unlock Step-by-Step Solutions & Ace Your Exams!

  • Full Textbook Solutions

    Get detailed explanations and key concepts

  • Unlimited Al creation

    Al flashcards, explanations, exams and more...

  • Ads-free access

    To over 500 millions flashcards

  • Money-back guarantee

    We refund you if you fail your exam.

Over 30 million students worldwide already upgrade their learning with Vaia!

Key Concepts

These are the key concepts you need to understand to accurately answer the question.

Floating-Point Precision
Floating-point precision is a key concept in computations involving real numbers on a computer. It refers to how precisely numbers can be represented by the floating-point system. Most real numbers do not have an exact representation in binary, which is why floating-point numbers are approximations rather than exact values.
It's important to remember that even seemingly simple numbers can turn into repeating binaries which cannot be exactly stored in computer memory. Instead, they are rounded to fit into the available bits.
As a result, calculations using floating-point arithmetic inherently involve small errors. This is particularly evident when performing arithmetic operations like addition, subtraction, multiplying, and division. These operations can introduce very slight inaccuracies that, over many calculations, accumulate into meaningful errors.
Knowing about and accounting for floating-point precision is vital in fields like numerical computing and scientific calculations where precision is critical.
Round-Off Errors
Round-off errors are those tiny inaccuracies that occur because of floating-point precision limitations. They are the result of attempting to represent floating numbers that are too long or complex in a finite binary system.
Consider the example where you are dividing 1 by 947 and then multiplying by 947 again. Ideally, the result should be 1, but due to the inability of computers to exactly represent the division results, a slight error might be introduced.
  • These errors are often quite small but can lead to unexpected results, particularly when comparing numbers.
  • In programming, you should avoid directly comparing floating-point numbers using `==` or `!=`. Instead, check if the numbers are close within a certain tolerance.
Understanding and managing these errors prevents erroneous computation results in sensitive applications.
Tolerance Levels
Tolerance levels play a crucial role in managing comparison operations of floating-point numbers effectively. They allow a margin of error when determining if two numbers are 'close enough' to be considered equal.
Instead of the strict equality `a == b`, you compare if `|a - b| < tolerance` where tolerance is a small, defined value like `1e-9`. This strategy accommodates the tiny inaccuracies stemming from floating-point calculations.
The selection of tolerance levels is significant because it accounts for the degree of accuracy necessary in your specific application. It's a balancing act—too large a tolerance and you might overlook significant differences, too small and minor errors can be mistaken for critical ones.
Careful tuning of the tolerance level helps improve the reliability and accuracy of your computing results, especially when dealing with minimal error margins in scientific data.
Python Programming
Python is a popular language for implementing floating-point arithmetic and examining its challenges, such as precision issues and round-off errors. Python provides several tools to help manage these challenges, making it a preferred choice in many scientific computations.
When working with floating-point numbers, Python allows you to adjust how comparisons are made by offering utilities for tolerance comparisons. For example, libraries like `SciTools` offer a function called `float_eq`, which compares two numbers within a defined tolerance level.
Python's flexibility, combined with its robust library ecosystem, makes it a powerful tool for scientific computing. Understanding how to handle floating-point arithmetic effectively in Python will prevent common pitfalls, such as incorrect results from direct comparison of floating-point numbers.
Scientific Computing
Scientific computing involves using computational methods and algorithms to solve scientific and engineering problems. This field frequently involves floating-point arithmetic, where precision and accuracy are imperative due to the complexity and scale of computations.
In scientific computing, floating-point precision is critical because the results influence real-world decisions. A small error in the computation of simulations, data analysis, or even financial models could lead to substantial errors in results.
Thus, understanding concepts like floating-point precision, round-off errors, and setting appropriate tolerance levels is essential for reliable results. Engineers, scientists, and analysts depend on these principles to achieve high accuracy in their computational tasks.
  • Floating-point arithmetic is prevalent in software used for weather forecasting, molecular modeling, and financial calculations.
  • To achieve precision, strategies like using tolerances and choosing the right algorithms and libraries are employed.
Grasping these concepts empowers one to better handle computational inaccuracies and enhance the fidelity of scientific analyses.

One App. One Place for Learning.

All the tools & learning materials you need for study success - in one app.

Get started for free

Most popular questions from this chapter

interest rate amount = initial_amount years = 0 while amount <= 1.5*init… # Consider the following program for computing with interest rates: initial_amount = 100 p = 5.5 # interest rate amount = initial_amount years = 0 while amount <= 1.5*initial_amount: amount = amount + p/100*amount years = years + 1 print years (a)Explain with words what type of mathematical problem that is solved by this program. Compare this computerized solution with the technique your high school math teacher would prefer. (b)Use a pocket calculator (or use an interactive Python shell as substitute) and work through the program by hand. Write down the value of amount and years in each pass of the loop. (c) Change the value of \(p\) to 5 . Why will the loop now run forever? (See Exercise \(2.12\) for how to stop the program if you try to run it.) Make the program more robust against such errors. (d)Make use of the operator += wherever possible in the program. Insert the text for the answers to (a) and (b) in a multi-line string in the program file. Name of program file: interest_rate_loop.py.

Write a program that prints a table with \(t\) values in the first column and the corresponding \(y(t)=v_{0} t-0.5 g t^{2}\) values in the second column. Use \(n\) uniformly spaced \(t\) values throughout the interval \(\left[0,2 v_{0} / g\right] .\) Set \(v_{0}=1, g=9.81\), and \(n=11\). Name of program file: ball_table1.py. \(\diamond\)

Rewrite the generation of the nested list q, $$ \mathrm{q}=[r * * 2 \text { for } \mathrm{r} \text { in }[10 * * \mathrm{i} \text { for } \mathrm{i} \text { in } \mathrm{range}(5)]] $$ by using standard for loops instead of list comprehensions. Name of program file: listcomp2for.py.

Study the following interactive session and explain in detail what happens in each pass of the loop, and use this explanation to understand the output. >>> numbers = range(10) >>> print numbers [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> for n in numbers: ... i = len(numbers)/2 ... del numbers[i] ... print ’n=%d, del %d’ % (n,i), numbers ... n=0, del 5 [0, 1, 2, 3, 4, 6, 7, 8, 9] n=1, del 4 [0, 1, 2, 3, 6, 7, 8, 9] n=2, del 4 [0, 1, 2, 3, 7, 8, 9] n=3, del 3 [0, 1, 2, 7, 8, 9] n=8, del 3 [0, 1, 2, 8, 9] The message in this exercise is to never modify a list that is used in \(a\) for loop. Modification is indeed technically possible, as we show above, but you really need to know what you are dingo - to avoid getting frustrated by strange program behavior. \(\diamond\)

Set a variable primes to a list containing the numbers \(2,3,5,7\) 11 , and \(13 .\) Write out each list element in a for loop. Assign 17 to a variable \(\mathrm{p}\) and add \(\mathrm{p}\) to the end of the list. Print out the whole new list. Name of program file: primes.py.

See all solutions

Recommended explanations on Computer Science Textbooks

View all explanations

What do you think about this solution?

We value your feedback to improve our textbook solutions.

Study anywhere. Anytime. Across all devices.

Sign-up for free