def _add(a, b): assert isinstance(a, FixedPoint) assert isinstance(b, FixedPoint) promoted_qformat = QFormat.from_qformats(a.qformat, b.qformat) result_qformat = QFormat(promoted_qformat.integer_bits + 1, promoted_qformat.fraction_bits) lhs_op = FixedPoint(a, result_qformat) rhs_op = FixedPoint(b, result_qformat) result_numerator = lhs_op._numerator + rhs_op._numerator return FixedPoint._from_numerator(result_numerator, result_qformat)
def _truediv(dividend, divisor): assert isinstance(dividend, FixedPoint) assert isinstance(divisor, FixedPoint) result_qformat = QFormat(dividend.qformat.integer_bits + divisor.qformat.fraction_bits + 1, divisor.qformat.integer_bits + dividend.qformat.fraction_bits) working_qformat = QFormat.from_qformats(dividend.qformat, divisor.qformat, result_qformat) lhs_op = FixedPoint(dividend, working_qformat) rhs_op = FixedPoint(divisor, working_qformat) # We use Fraction's round() here rather than floor division to get correct rounding working_numerator = round(Fraction(lhs_op._numerator * working_qformat.denominator, rhs_op._numerator)) working_result = FixedPoint._from_numerator(working_numerator, working_qformat) return FixedPoint(working_result, result_qformat)
def _truediv(dividend, divisor): assert isinstance(dividend, FixedPoint) assert isinstance(divisor, FixedPoint) result_qformat = QFormat( dividend.qformat.integer_bits + divisor.qformat.fraction_bits + 1, divisor.qformat.integer_bits + dividend.qformat.fraction_bits) working_qformat = QFormat.from_qformats(dividend.qformat, divisor.qformat, result_qformat) lhs_op = FixedPoint(dividend, working_qformat) rhs_op = FixedPoint(divisor, working_qformat) # We use Fraction's round() here rather than floor division to get correct rounding working_numerator = round( Fraction(lhs_op._numerator * working_qformat.denominator, rhs_op._numerator)) working_result = FixedPoint._from_numerator(working_numerator, working_qformat) return FixedPoint(working_result, result_qformat)