0

I am trying to perform a divide operation in python, (3000/365)*365 which prints 3000.0000000000005. Whereas in actual this should return 3000?

Can someone help me understand what am I missing here?

  • result for `(3000/365)*3000` should be `24657.534246575346` – Nitin Goyal Dec 21 '20 at 07:15
  • My bad a typo, apologies it is (3000/365)*365 – Catalyst1829 Dec 21 '20 at 07:18
  • 1
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – user2390182 Dec 21 '20 at 07:20
  • As pointed out by others, what you're seeing is the result of floating point arithmetic. You might also be interested in exact decimal arithmetic. I think there are probably implementations of that for Python; a web search should find some resouces. – Robert Dodier Dec 21 '20 at 19:51

2 Answers2

0

Programming languages has floting point precesion errors. which cause sometime this kind of issues.

https://docs.python.org/3/tutorial/floatingpoint.html

Is floating point math broken?

Nitin Goyal
  • 497
  • 4
  • 16
0

As mentioned above, it is because of the precision when using floating points.

A solution would be to round the result:

(round(3000/365*365,2)

and if you don't want a float, you could use int

int((round(3000/365*365,2))

Not sure if there is another approach, but hope this helps.

Gabu
  • 51
  • 1
  • 2