francof2a / fxpmath

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

Feature Request: New rounding mode #86

Open danilo-bc opened 11 months ago

danilo-bc commented 11 months ago

Another fixed-point standard, included in IEEE's SystemC, has a mode SC_RND described in their manual, section 7.10.9.12 which states

This rule shall be used for all rounding modes when the two nearest representable numbers are not at equal distance. When the two nearest representable numbers are at equal distance, this rule implies that there is rounding toward plus infinity [...].

This means that it isn't compatible with any current rounding mode, including 'around', which uses even rounding.

A practical example:

x = Fxp(0.1689453125, n_word = 12, n_int = 2, rounding='around')
#                                       fxp-s12/9(0.16796875)
# Expected value for new rounding mode: fxp-s12/9(0.169921875)
nozomioshi commented 4 months ago

Prior to the release of v0.5.0, some data preprocessing can be performed by adjusting the values slightly through addition or subtraction of a extremely small number, in order to achieve the desired rounding effect. An example for complex numbers in numpy.ndarray:

        precision = Fxp(signed=signed, n_word=n_word, n_frac=n_frac, rounding=rounding).precision
        if isinstance(data, np.ndarray):
            if isinstance(data.item(0), complex):
                data = data + np.sign(data.real)*precision*1e-8 + 1j*np.sign(data.imag)*precision*1e-8

    return Fxp(data, signed=signed, n_word=n_word, n_frac=n_frac, rounding=rounding)