Search code examples
clojurebigdecimalarbitrary-precision

Clojure bigdec division rules


I am hitting a floating-precision problem : one of my results of dividing between Doubles and/or Long gives me 2.8421709430404007E-14 instead of 0.

So I guess I have to use BigDecimals (bigdec more precisely).

My question is :

  • will operations involving a bigdec convert all other numbers involved in the operation to a suitable type ?
  • is there an operation that does that ? I am basically looking for the equivalent of *', but /' doesn't seem to exist.

Solution

    1. If you use any doubles (or floats) in your computation, the final result will be a double.

    2. Otherwise any computation involving BigDecimals will return a BigDecimal result or throw an exception.

    3. Exceptions might be thrown if the result cannot be represented exactly, if some intermediate computation causes long overflow, or if you divide by zero.

    4. +' etc. promote to BigInteger where + would cause integer overflow.

    5. Rounding can be introduced to deal with exact representation issues – see (doc with-precision).