There's something wrong with my understanding of either the round function in python or how doubles are represented in python. I find a very perplexing behavior when rounding numbers that have a double precision rounding error; for example 1.01046+.00002=1.0104799999999998. When I round this to 5 digits, python reports the result as 1.01048, the expected result. But I thought the whole issue was that 1.01046+.00002=1.0104799999999998 because there's no double value that exactly equals 1.01048. If round takes in a double and returns a double, how can it return 1.01048 if no such double exists?
The following code:
print([1.01046+.00002*i for i in range(6)])
outputs:
[1.01046, 1.0104799999999998, 1.0105, 1.0105199999999999, 1.01054, 1.01056]
wheras this code:
print([round(1.01046+.00002*i,5) for i in range(6)])
outputs:
[1.01046, 1.01048, 1.0105, 1.01052, 1.01054, 1.01056]
why is it that python doesn't have an exact value for 1.01046+.00002*1, python says "I don't have any such number; I can give you a number that's really close though", but when I ask python to round the resulting number, it goes "oh yeah of course that's 1.01048"
The result of rounding isn't exact, either. But when numbers are printed, there's a default number of significant digits, and it's close enough that it gets printed without any trailing errors.
You can see this if you force the output to 20 digits after the decimal point.
In the cases where
valandround(val, 5)are different, the difference is after the 16th digit after the decimal point, and that's not shown by default.