Issue
I am trying to compare accuracies between adding multiple floats together versus adding multiple decimals together for a lab in my Python course. One of the requirements of the lab is to count how many iterations of adding .1 results in the correct sum. Everything in my code works properly except for my counter for how many additions were correct for the decimal additions. For 100 iterations it only counts 20 as being correct (every 5 iterations) even though I have proven them all to be correct by printing each iteration. Why is this happening and how can this be fixed? Thanks. (You can find the complete code below to get the full context as well as the output.)
Code:
from decimal import *
floatSum = 0
decSum = 0
toAddFloat = .1
toAddDec = Decimal(".1")
max = 100 # number of iterations
floatCorrect = 0
decCorrect = 0
# continually add .1 as floats together for specified number of iterations
for i in range (0, max, 1):
floatSum = floatSum + toAddFloat
print(floatSum,(i + 1) / 10)
if (floatSum == (i + 1) / 10): # check if the addition is what it should be
floatCorrect += 1
i = 0
# continually add .1 as decimals together for specified number of iterations
for i in range (0, max, 1):
decSum = decSum + toAddDec
print(decSum, (i + 1) / 10)
print(decCorrect)
if (decSum == (i + 1) / 10): # check if the addition is what it should be
decCorrect += 1
print("\nFLOAT RESULTS:")
print("--------------")
print("Iterations: ", max, ", Added Number: ", toAddFloat, ", Calculated Sum: ", floatSum,
", Times Correct: ", floatCorrect, ", Correct Result: ", toAddFloat * max, ", Difference: ", (toAddFloat * max) - floatSum, "\n")
print("DECIMAL RESULTS:")
print("----------------")
print("Iterations: ", max, ", Added Number: ", toAddDec, ", Calculated Sum: ", decSum,
", Times Correct: ", decCorrect, ", Correct Result: ", toAddDec * max, ", Difference: ", (toAddDec * max) - decSum)
(partial) Output:
FLOAT RESULTS:
--------------
Iterations: 100 , Added Number: 0.1 , Calculated Sum: 9.99999999999998 , Times Correct: 11 , Correct Result: 10.0 , Difference: 1.9539925233402755e-14
DECIMAL RESULTS:
----------------
Iterations: 100 , Added Number: 0.1 , Calculated Sum: 10.0 , Times Correct: 20 , Correct Result: 10.0 , Difference: 0.0
Solution
update this line to
if (decSum*10 == (i + 1)):
for python division gives a float point result. if this number does not have precise presentation as it looks, it won;t equal to the decimal counterpart.
Answered By - Bing Wang Answer Checked By - Pedro (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.