[CLJ-1006] Quotient on bigdec may produce wrong result Created: 01/Jun/12 Updated: 01/Mar/13 Resolved: 09/Nov/12 |
|
| Status: | Closed |
| Project: | Clojure |
| Component/s: | None |
| Affects Version/s: | Release 1.4 |
| Fix Version/s: | None |
| Type: | Defect | Priority: | Major |
| Reporter: | laurent joigny | Assignee: | Unassigned |
| Resolution: | Declined | Votes: | 0 |
| Labels: | bug | ||
| Environment: |
Linux 3.2.0-24-generic #39-Ubuntu SMP i686 GNU/Linux |
||
| Attachments: |
|
| Description |
|
Hi, As discussed on the mailing list in the message "When arithmetic on a computer bite back" (01/jun) There may be bug in the way quotient is implemented for bigdec. user> (quot 1.4411518807585587E17 2) ;; correct with doubles – |
| Comments |
| Comment by laurent joigny [ 01/Jun/12 5:48 PM ] |
|
I can reproduce the bug when using BigDecimal constructor on String. More infos : |
| Comment by laurent joigny [ 01/Jun/12 5:49 PM ] |
|
A simple test file, that you can drop in Clojure sources and execute to reproduce the bug on BigDecimal constructor using String as argument. |
| Comment by Tassilo Horn [ 03/Jun/12 4:30 AM ] |
|
Seems to be a general precision problem. Note that in user> (quot 1.4411518807585587E17 2) ;; correct with doubles 7.2057594037927936E16 user> (quot 1.4411518807585587E+17M 2) ;; wrong with BigDecs 72057594037927935M the double result is actually wrong and the bigdec one is correct. The problem which lead to the wrong conclusion is that in your calculation the input number is already wrong. So the moral is: don't use any floating points (neither doubles nor bigdecs) for computations involving divisibility tests. For bigdecs, you can set the math context for making computations throw exceptions if they lose precision, though: user> (binding [*math-context* (java.math.MathContext. 1 java.math.RoundingMode/UNNECESSARY)] (quot (bigdec (Math/pow 2 58)) 2)) ;Division impossible ; [Thrown class java.lang.ArithmeticException] |
| Comment by Stuart Sierra [ 09/Nov/12 8:49 AM ] |
|
Not a bug. Just floating-point arithmetic. |