Question: In this lab, we will explore some floating-point issues . Please complete the steps below in order. Part 1: Demonstrating the problem - Using the
In this lab, we will explore some floating-point issues. Please complete the steps below in order.
Part 1: Demonstrating the problem
- Using the Python IDLE, run the following from the shell window and observe what happens.
print(.1+.1 == .2)
print(.1+.1+.1 ==.3)
print(.1+.1+.1 + .1 ==.4)
PYTHON CODE
sum = 0
toAdd = .1
max = ENTER NUMBER OF ITERATIONS HERE
for i in range (0, max, 1):
sum = sum + toAdd
print(sum, i)
#ADD A PRINT STATEMENT HERE THAT PRINTS (WHEN THE LOOP IS FINISHED) THE NUMBER OF ITERATIONS, THE NUMBER YOU ADDED, THE SUM YOU CALCULATED, AND THE DIFFERENCE BETWEEN THE CORRECT RESULT AND YOUR SUM
Part 2: Estimating the error - Use the given code.
- Fill in the missing pieces of the above code
- Run the loop for 100 iterations. For how many numbers do you get the correct result? - Remove the print statement IN the loop
- Run the loop for 10, 100 and 1000 iterations. Explore how the difference between what you should get and what you do get behaves as the number of iterations changes
- Estimate how many iterations would be needed to have an error that is as large as the number you add.
Part 3: Estimating the scope of the problem
- Using your code, find two more numbers between 0 and 1 for which there are also incorrect results for 100 iterations
- Using your code, find two numbers for which the result is correct.
- Do some research online to figure out the reason why some numbers that you add repeatedly end up in the correct result, and why some others are not
Part 4: One potential solution
- Import the decimal package to your code
- ADD to your file a second loop that does exactly the same as the first loop but now using a decimal number repeatedly. You will have to make sure that all operations are done using decimals
- How does the error behave as you run the code for 10, 100 and 1000 iterations? Is it better or worse than using Pythons default floating datatype
- Do some research on the decimal module, and figure out the reason for the result
Submit the code file for Part 4 that includes your observations and reasons for each of the parts at the top as a comment.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
