1

I'm using the modulus operator and I'm get some floating point errors. For example,

>>> 7.2%3
1.2000000000000002

Is my only recourse to handle this by using the round function? E.g.

>>> round(7.2%3, 1)
1.2

I don't a priori know the number of digits I'm going to need to round to, so I'm wondering if there's a better solution?

wogsland
  • 9,106
  • 19
  • 57
  • 93
  • Consider using `decimal.Decimal`? – Mariy Mar 12 '17 at 20:39
  • Floating-point numbers do not represent exact values. You introduced inaccuracy into your program the moment you wrote ``7.2``. If your program can't live with a trillionth of a percent error, you need to use a decimal or rational data type. – jasonharper Mar 12 '17 at 20:40
  • I think this has been answered here. Because Math is weird. http://stackoverflow.com/questions/14763722/python-modulo-on-floats?answertab=active#tab-top – Thomas Stefan Wire Mar 12 '17 at 20:43

1 Answers1

4

If you want arbitrary precision, use the decimal module:

>>> import decimal
>>> decimal.Decimal('7.2') % decimal.Decimal('3')
Decimal('1.2')

Please read the documentation carefully.

Notice I used a str as an argument to Decimal. Look what happens if I didn't:

>>> decimal.Decimal(7.2) % decimal.Decimal(3)
Decimal('1.200000000000000177635683940')
>>>
juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172
  • So I need to make sure I `str()` the numbers before passing them to `Decimal`. Got it. Thanks! – wogsland Mar 12 '17 at 20:42
  • 1
    @wogsland I would be careful with `str`, which automatically rounds, but floating point errors can creep into the rounding. Use string literals where possible. – juanpa.arrivillaga Mar 12 '17 at 20:46