2

I am using python 3.6.8 and tried to multiply 0.1235 with 10 and the answer is 1.2349999999999999 rather than 1.235. After importing the decimal module, when we multiply decimal.Decimal(0.1235) with 10 we get Decimal('1.234999999999999986677323704') rather than Decimal('1.235'). So How to do precision float calculations with python?

  • 1
    Note: If you want decimal accurate math, use the `decimal` module (or the `fractions` module for other use cases). Binary floating point is intrinsically unable to perform perfectly accurate decimal math. – ShadowRanger Jun 02 '20 at 22:05
  • 1
    @AsishKumar: If you read the docs, initializing a `Decimal` from a `float` preserves the idiosyncrasies of the underlying float representation (which is not in fact `0.1235`, as `0.1235` is just a way to write the number that is ever-so-slightly less than that, and the closest `float` representation can get to `0.1235`). You need to initialize with `int`s (for non-float stuff) or `str` (for anything); `Decimal("0.1235")` will work just fine. – ShadowRanger Jun 02 '20 at 22:25

1 Answers1

1

The value 0.1235 is a decimal fraction that needs to be converted to a binary fraction in memory, resulting in not a 100 percent accuracy. please refer to Floating Point Arithmetic: Issues and Limitations

CtrlMj
  • 119
  • 7