0

The built-in float can't keep the precison(eg.float('123.45678' = 123.45677999999999), I rewrite it, but also meet the same problem. My question is as the title.

a_int = lambda s : sum(((ord(s[j])-48)*(10**(len(s)-j-1)) for j in range(len(s))))

def a_float(s):
    l = s.split(".")
    return a_int(l[0]+l[1]) / 10.0**len(l[1])

>>> s = "11223.512512"
>>> a_float(s)
11223.512511999999
2
  • 2
    You can't. That's the nature of floating point values. See docs.python.org/2/tutorial/floatingpoint.html Commented Sep 17, 2014 at 16:23
  • 2
    I strongly recommend not rewriting float: getting fast and correct decimal-to-binary conversions is hard! Commented Sep 17, 2014 at 16:31

1 Answer 1

3

Floating point values are not precise. They are binary fraction approximations instead; e.g. the computer adds up 1/2 + 1/4 + 1/8, etc. (but picking those fractions based on your actual value), adding those up to approximate the decimal value. A float value can simply not represent the value 11223.512512 precisely. This is the price of hardware-acceleration support; float operations are extremely fast, and usually precise enough.

Don't use float values if precision is important; use the decimal.Decimal() type instead. Or decide on how many digits you want to represent when printing, and format your floating point values with format():

print format(a_float(s), '.6f')

I recommend you read the Floating Point Arithmetic: Issues and Limitations chapter of the Python tutorial for more details.

Sign up to request clarification or add additional context in comments.

2 Comments

It is not so much a matter of precision than of exact representation of decimal fractions. A decimal type has the same problem representing one third.
@PatriciaShanahan: The OP is not talking about fractions here though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.