Skip to content

add MathUtil#1092

Merged
pjfanning merged 1 commit into
apache:trunkfrom
pjfanning:mathutil
May 27, 2026
Merged

add MathUtil#1092
pjfanning merged 1 commit into
apache:trunkfrom
pjfanning:mathutil

Conversation

@pjfanning
Copy link
Copy Markdown
Member

can make more of use of it in later commits and also need to extend test coverage

@pjfanning pjfanning merged commit b7f72c8 into apache:trunk May 27, 2026
1 check passed
@pjfanning pjfanning deleted the mathutil branch May 27, 2026 14:01
}

public static int safeDoubleToInt(double d) {
if (Double.isNaN(d)) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know how much of a difference this makes (it could when used in a tight loop), but only one check is necessary. If we use Double.isFinite() instead, it will also catch NaN. Double.isFinite(Double.NaN) returns false just as Double.isInfinite(Double.NaN), the functions are not symmetric in this aspect. So this should catch both:

        if (!Double.isFinite(d)) { // DO NOT REPLACE WITH Double.isInfinite(d) !!!
            throw new IllegalArgumentException("Cannot convert number to int: " + d);
        }

}
@Override
public int getAlpha() { return (int)Math.round(color.getAlpha()*100000./255.); }
public int getAlpha() { return Math.toIntExact(Math.round(color.getAlpha()*100000./255.)); }
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this would be a good candidate for the new MathUtil class:

public static int roundToInt(double d) {
    return safeDoubleToInt(Math.rint(d));
}

I used your rint() version I discovered below because it will handle infinity and NaN correcty.

}

return (int)Math.rint(targetSize);
return MathUtil.safeDoubleToInt(Math.rint(targetSize));
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think should use a method in MathUtil (as described above). Actually using MathUtil.safeDoubleToInt(Math.rint(...)) seems like a good idea as infinity and NaN should be handled correctly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants