What would be the simplest formula to implement int divround(int a, int b) {...}, in C, where output is a/b with banker's rounding (round half to even)?
For example, divround(3,2) and divround(5,2) both evaluate to 2.
I'm writing embedded code, so I cannot rely on libraries. I want the code to be generic for ARM and RISC-V, so no assembly as well. I'm trying to mimick the behavior of np.around(a/b) in NumPy (which performs round half to even), so I can exactly compare output test vectors from Python and my embedded application.
Assuming
aandbare nonnegative, andbis less thanINT_MAX / 2, the following is a simple implementation:For an explanation:
bround up and if it's less round down.b/2exactly, then check if the quotient is even, and if so round down otherwise round up.If you also want to handle negative values, first determine the sign of the result and normalize the values to nonnegative, then perform the above while multiplying the sign to the result. Works assuming
bis betweenINT_MIN / 2andINT_MAX / 2.And of course, don't divide by 0.