# File: roundoff.py # Demonstrate round-off error # # Matt Bishop, MHI 289I, Fall 2021 # # First, set x to 1.0 and print it x = 0.1 print("This should print the value of x as 0.1:", x) # # Now, add x to itself 10 times and print the value y = x + x + x + x + x + x + x + x + x + x print("This should print 1.0, the value of x added to itself 10 times:", y) # # Now compare it to 1.0 -- note it's not the same! print("Now compare y to 1.0:", y == 1.0) # # And here's why -- go out to 20 decimal places print("The actual value of y, to 20 places:", "%.20f" % y) # pause input(">>>") # # Now, multiply x by 10 and print the value y = 10 * x print("This should print 1.0, the value of x multiplied by 10:", y) # # Now compare it to 1.0 -- note it's the same! print("Now compare y to 1.0:", y == 1.0) # pause input(">>>") # # Now, multiply x by 12 and print the value y = 12 * x print("This should print 1.2, the value of x multiplied by 12:", y) # # Now compare it to 1.2 -- note it's not the same! print("Now compare y to 1.2:", y == 1.2) # # And here's why -- go out to 20 decimal places print("The actual value of y, to 20 places:", "%.20f" % y) # #