This repository has been archived on 2021-05-25. You can view files and clone it, but cannot push or open issues or pull requests.
pyRCV2/pyRCV2/numbers/rational_py.py

47 lines
1.8 KiB
Python
Raw Normal View History

2020-10-17 18:40:18 +11:00
# pyRCV2: Preferential vote counting
# Copyright © 2020–2021 Lee Yingtong Li (RunasSudo)
2020-10-17 18:40:18 +11:00
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from pyRCV2.numbers.base import BasePyNum, compatible_types
2020-10-17 22:20:13 +11:00
from fractions import Fraction
import math
2020-10-17 22:20:13 +11:00
class Rational(BasePyNum):
2020-10-18 03:25:41 +11:00
"""
Wrapper for Python Fraction (rational arithmetic)
"""
_py_class = Fraction # For BasePyNum
2020-10-17 22:20:13 +11:00
def pp(self, dp):
"""Overrides BasePyNum.pp"""
2020-12-23 21:39:43 +11:00
# TODO: Work out if there is a better way of doing this
return format(float(self.impl), '.{}f'.format(dp))
2020-10-17 18:40:18 +11:00
def round(self, dps, mode):
"""Implements BaseNum.round"""
factor = Fraction(10) ** dps
if mode == Rational.ROUND_DOWN:
2021-01-01 22:26:57 +11:00
return Rational._from_impl(math.floor(self.impl * factor) / factor)
elif mode == Rational.ROUND_HALF_UP: # pragma: no cover
raise NotImplementedError('ROUND_HALF_UP is not implemented in Python Rational context')
elif mode == Rational.ROUND_HALF_EVEN:
2021-01-01 22:26:57 +11:00
return Rational._from_impl(round(self.impl * factor) / factor)
elif mode == Rational.ROUND_UP:
2021-01-01 22:26:57 +11:00
return Rational._from_impl(math.ceil(self.impl * factor) / factor)
else: # pragma: no cover
raise ValueError('Invalid rounding mode')