numpy/numpy-user-dtypes

quaddtype `rint` wrong for near-halfway case

Closed this issue · 1 comments

> np.rint(numpy_quaddtype.SleefQuadPrecision("7.4999999999999999"))
QuadPrecision('7.0e+000', backend='sleef') # as expected

> np.rint(numpy_quaddtype.SleefQuadPrecision("7.49999999999999999"))
QuadPrecision('8.0e+000', backend='sleef') # this is wrong

> numpy_quaddtype.SleefQuadPrecision("7.49999999999999999")
QuadPrecision('7.49999999999999999e+000', backend='sleef') # the number can be represented as <7.5

It seems the following workaround produces the expected result:

def rint(a: np.ndarray) -> np.ndarray:
    halfway = np.trunc(a) + np.where(a < 0, a.dtype.type(-0.5), a.dtype.type(0.5))

    return np.where(
        a == halfway,
        np.rint(a),
        np.where(a < halfway, np.floor(a), np.ceil(a)),
    )