1

I have two numbers a and b: a = 1562239482.739072 b = 1562239482.739071

If I perform a-b in python, I get 1.1920928955078125e-06. However, I want 0.000001, which is the right answer after subtraction.

Any help would be appreciated. Thank you in advance.

t = float(1562239482.739071)
T = float(1562239482.739072)
D = float(T - t)
print(float(D))

OR

t = 1562239482.739071
T = 1562239482.739072
D = T - t 
print (D)

I get the same answer 1.1920928955078125e-06 using both as mentioned above. However, I want the result 0.000001.

Expected Result: 0.000001 Result : 1.1920928955078125e-06

2 Answers2

-1

This is common problem with floating point arithmetic. Use the decimal module

smac89
  • 39,374
  • 15
  • 132
  • 179
  • `decimal` is still floating point. It's just decimal, configurable-precision floating point. Rounding problems still happen. The fact that printed and internal representations are both decimal makes rounding more intuitive, but it doesn't eliminate the problem. – user2357112 Jul 14 '19 at 03:10
  • "Use the `decimal` module" is a bad, misleading answer without explaining what the `decimal` module does and does not actually offer. – user2357112 Jul 14 '19 at 03:11
  • 1
    For one thing, an answer is supposed to stand on its own without reading links. For another, you're presenting the `decimal` module as if simply using it will automatically solve this category of problem. – user2357112 Jul 14 '19 at 03:33
-2

you can use Decimal like

from decimal import Decimal

a=Decimal('1562239482.739071')

b=Decimal('1562239482.739072')

c= b - a

print(c)

That will be the answer you want

Sun
  • 1
  • 1