commons-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Phil Steitz (JIRA)" <>
Subject [jira] Commented: (MATH-151) MathUtils.round incorrect result
Date Sun, 11 Jun 2006 16:58:30 GMT
    [ ] 

Phil Steitz commented on MATH-151:

I understand and agree with your analysis of the IEEE754 representation, but I would still
like to see if there is anyting clever that we can do to work around the problem.   Could
be this is hopeless, but I am bothered by the fact that the previous implementation actually
handles this correctly.  Sorry I messed up the link in the comment above to the earlier BigDecimal-based
impl.  That should have been to

In any case, the impl there, modified to handle the special values included in later tests
would be:
public static double round(double x, int scale, int roundingMethod) {
        try {
            return (new BigDecimal
                   (new Double(x).toString())
                   .setScale(scale, roundingMethod))
        } catch (NumberFormatException ex) {
            if (Double.isInfinite(x)) {
                return x;          
            } else {
                return Double.NaN;

Before, it was just
return (new BigDecimal(x).setScale(scale, roundingMethod))

The code above passes all tests, including even
double x = 39.0d;
x = x + 245d/1000d;
assertEquals(39.25,MathUtils.round(x, 2), 0.0);

> MathUtils.round incorrect result
> --------------------------------
>          Key: MATH-151
>          URL:
>      Project: Commons Math
>         Type: Bug

>     Versions: 1.1 Final
>  Environment: Win2K, Sun JDK1.5.0_05 b05
>     Reporter: Buza Zoltán

> MathUtils.round(39.245, 2) results 39.24, however it should be 39.25, with default rounding
mode BigDecimal.ROUND_HALF_UP.
> I found that internally MathUtils.round multiplies the given number by 10^scale.
>  39.245 * 100.0 results 3924.49999...5 , and after this the calculation is not correct
any more.

This message is automatically generated by JIRA.
If you think it was sent incorrectly contact one of the administrators:
For more information on JIRA, see:

To unsubscribe, e-mail:
For additional commands, e-mail:

View raw message