Last active
July 13, 2016 01:26
-
-
Save notesbytom/10fb8e6a6dca3f39cb5237af7a3f1146 to your computer and use it in GitHub Desktop.
Demonstrate Binary Floating Point Behavior with Decimal Fractions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Note that standard binary computing floating point numbers cannot exactly represent simple decimal floating point numbers. | |
# This is the expected behavior for IEEE-754 compliant binary floating point processors | |
# https://en.wikipedia.org/wiki/IEEE_floating_point | |
# Case in point, 0.1 (1/10 = 10^-1) is between 1/8=2^-3 and 1/16=2^-4 | |
# Since binary fraction cannot exacly store 1/10, accuracy of associated arithmetic is adversely impacted | |
# https://docs.python.org/3.5/tutorial/floatingpoint.html | |
# See the following example using Python 3.x | |
def test_binary_fraction(): | |
mySum = 0 | |
for i in range(10): | |
mySum += .1 | |
print("0.1 Added Ten Times = {}, (expected 1.0)".format(mySum)) | |
print("Subtract result from 1.0 = {}, (expected 0.0)".format(1.0-mySum)) | |
test_binary_fraction() | |
# Sample Output ... | |
# 0.1 Added Ten Times = 0.9999999999999999, (expected 1.0) | |
# Subtract result from 1.0 = 1.1102230246251565e-16, (expected 0.0) | |
# For many applications, the default approximation in binary will be acceptable. | |
# To more precisely handle Decimal floating point numbers, we can use alternate | |
# arithmetic and math capabilities such as the Python "decimal" module | |
# https://docs.python.org/3.5/library/decimal.html |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment