Replies: 1 comment
-
This is an interesting topic, with the issue of how to round negative numbers being perhaps the most puzzling. For my own work, mostly in CAD, I've found that rounding in a consistent fashion, where 0 is no more significant that any other place on the number line, doing a rounding equivalent to floor( n + 0.5 ) is best, but this is not how C++ does rounding with round() or lround(), where -2.5 rounds to -3.0. Thus in C#, I would choose a MidpointRounding of ToPositiveInfinity rather than AwayFromZero. One way to think about this is to consider two points, x and y, stored in floating point. Round the values and take their difference. Now translate the points equivalently, and do it again. Would you want the new difference to be the same as the first?
At the end of the above C++ example, delta0 is 4.0 and delta1 is 5.0, but I would prefer a consistent result. It's possible that there are scenarios that would benefit from a different type of rounding, but I've had good luck with floor( n + 0.5 ). |
Beta Was this translation helpful? Give feedback.
-
Hey Angus,
In C sharp Math.Round per default does bankers rounding, which is IMHO unintuitive and possibly differs from other languages: 2.5 will be rounded to 2, and 3.5 will be rounded to 4. You can change this behavior to what we learned in school using the MidpointRounding option:
var test1 = Math.Round(2.5f, MidpointRounding.AwayFromZero);//should round to 3
var test2 = Math.Round(2.5f);//should round to 2
I am not aware of any bugs but could imagine this could lead to bugs in maybe merging polygons or small self intersections, so wanted to make you aware.
Edit: just checked:
In summary: for the midpoint (0.5), C++ and Java round to nearest int, C Sharp and Delphi to even number (bankers)
Beta Was this translation helpful? Give feedback.
All reactions