francof2a / fxpmath

A python library for fractional fixed-point (base 2) arithmetic and binary manipulation with Numpy compatibility.
MIT License
183 stars 21 forks source link

Feature request: round-to-even #51

Closed jrmoserbaltimore closed 2 years ago

jrmoserbaltimore commented 2 years ago

IEEE754 specifies a round-to-even method (among several, but this is apparently preferred) which solves an exact midpoint by rounding up if the last digit to be stored in the word width is 1, and rounding down if the last digit to be stored is zero. For example:

        1.000110
round:  1.0010
        1.000010
round:  1.0000
        1.000011
round:  1.0001

Since it's a common method, it may be useful in Fxpmath.

francof2a commented 2 years ago

Have you try rounding = 'around'?

Your examples would be as following:

x = Fxp('0b1.000110')
x_rounded = Fxp(x, dtype='S1.4', rounding='around')
x_rounded.bin(frac_dot=True)

'1.0010'

x = Fxp('b1.000010')
x_rounded = Fxp(x, dtype='S1.4', rounding='around')
x_rounded.bin(frac_dot=True)

'1.0000'

x = Fxp('0b1.000011')
x_rounded = Fxp(x, dtype='S1.4', rounding='around')
x_rounded.bin(frac_dot=True)

'1.0001'

jrmoserbaltimore commented 2 years ago

Evenly round of the given value to the nearest fractional supported value, for example: 1.5 is rounded to 2.0.

Ah. I misinterpreted this as meaning "round evenly," i.e. not truncate, floor, or ceiling, and assumed it meant the commonly used ties round up algorithm rather than ties round to even. I'm also not clear on the difference between trunc and fix, which both say they round to zero.

francof2a commented 2 years ago

According to Numpy's documentation and behavior, trunc and fix perform same rounding.

Please, let me know if you consider the issue solved.

francof2a commented 2 years ago

Closing the issue, please reopened if you consider unsolved. Thank you!