GitHub

Rational

API reference for Rational.

numerator / denominator in lowest terms with denominator > 0; use make or make_unsafe to reduce any other pair.

Attributes

AttributeTypeDescription
numeratorint
denominatorint

Functions

__init__

__init__(numerator, denominator) -> None
ParameterTypeDescription
numeratorint
denominatorint

format

format() -> str

"numerator/denominator", which from_string reads back.

Returns str

def format(self) -> str:
    """``"numerator/denominator"``, which ``from_string`` reads back."""
    return f"{int_text(self.numerator)}/{int_text(self.denominator)}"

to_json

to_json() -> dict[str, str]

Effect's toJSON.

Returns dict[str, str]

def to_json(self) -> dict[str, str]:
    """Effect's ``toJSON``."""
    return {
        "_id": "Rational",
        "numerator": int_text(self.numerator),
        "denominator": int_text(self.denominator),
    }

to_number_unsafe

to_number_unsafe() -> float

The nearest float, rounding the ratio once (ties to even, subnormals included); too large a magnitude is an infinity.

Returns float

def to_number_unsafe(self) -> float:
    """The nearest float, rounding the ratio once (ties to even, subnormals included);
    too large a magnitude is an infinity."""
    try:
        return self.numerator / self.denominator
    except OverflowError:
        return math.inf if self.numerator > 0 else -math.inf

to_big_decimal

to_big_decimal(*, scale, mode='half-from-zero') -> big_decimal.BigDecimal

The value rounded to scale digits after the point with mode.

ParameterTypeDescription
scaleint
modebig_decimal.RoundingMode = 'half-from-zero'

Returns big_decimal.BigDecimal

def to_big_decimal(
    self, *, scale: int, mode: big_decimal.RoundingMode = "half-from-zero"
) -> big_decimal.BigDecimal:
    """The value rounded to ``scale`` digits after the point with ``mode``."""
    if type(scale) is not int or not -_MAX_SAFE <= scale <= _MAX_SAFE:
        raise ValueError(f"Scale must be a safe integer, got {js_number(scale)}")
    numerator, denominator = self.numerator, self.denominator
    if scale >= 0:
        numerator *= 10**scale
    else:
        denominator *= 10**-scale
    quotient = abs(numerator) // denominator
    remainder = abs(numerator) - quotient * denominator
    if numerator < 0:
        quotient, remainder = -quotient, -remainder
    adjustment = _rounding_adjustment(quotient, remainder, denominator, mode)
    return big_decimal.make(quotient + adjustment, scale)

sign

sign() -> Literal[-1, 0, 1]

Returns Literal[-1, 0, 1]

def sign(self) -> Literal[-1, 0, 1]:
    return 0 if self.numerator == 0 else -1 if self.numerator < 0 else 1

is_zero

is_zero() -> bool

Returns bool

def is_zero(self) -> bool:
    return self.numerator == 0

is_negative

is_negative() -> bool

Returns bool

def is_negative(self) -> bool:
    return self.numerator < 0

is_positive

is_positive() -> bool

Returns bool

def is_positive(self) -> bool:
    return self.numerator > 0

is_integer

is_integer() -> bool

Returns bool

def is_integer(self) -> bool:
    return self.denominator == 1

sum

sum(that) -> Rational
ParameterTypeDescription
thatRational

Returns Rational

def sum(self, that: Rational) -> Rational:
    return _sum_coprime(self.numerator, self.denominator, that.numerator, that.denominator)

subtract

subtract(that) -> Rational
ParameterTypeDescription
thatRational

Returns Rational

def subtract(self, that: Rational) -> Rational:
    return _sum_coprime(self.numerator, self.denominator, -that.numerator, that.denominator)

multiply

multiply(that) -> Rational
ParameterTypeDescription
thatRational

Returns Rational

def multiply(self, that: Rational) -> Rational:
    return _multiply_coprime(self.numerator, self.denominator, that.numerator, that.denominator)

divide

divide(that) -> Rational | None

self / that, or None when that is zero.

ParameterTypeDescription
thatRational

Returns Rational | None

def divide(self, that: Rational) -> Rational | None:
    """``self / that``, or ``None`` when ``that`` is zero."""
    if that.numerator == 0:
        return None
    if that.numerator < 0:
        return _multiply_coprime(
            self.numerator, self.denominator, -that.denominator, -that.numerator
        )
    return _multiply_coprime(self.numerator, self.denominator, that.denominator, that.numerator)

divide_unsafe

divide_unsafe(that) -> Rational

self / that; raises ZeroDivisionError when that is zero.

ParameterTypeDescription
thatRational

Returns Rational

def divide_unsafe(self, that: Rational) -> Rational:
    """``self / that``; raises ``ZeroDivisionError`` when ``that`` is zero."""
    out = self.divide(that)
    if out is None:
        raise ZeroDivisionError("Division by zero")
    return out

pow

pow(exponent) -> Rational | None

self ** exponent, inverting for a negative exponent; None for zero to a negative power. The exponent must be a safe integer.

ParameterTypeDescription
exponentint

Returns Rational | None

def pow(self, exponent: int) -> Rational | None:
    """``self ** exponent``, inverting for a negative exponent; ``None`` for zero to a
    negative power. The exponent must be a safe integer."""
    if type(exponent) is not int or not -_MAX_SAFE <= exponent <= _MAX_SAFE:
        raise ValueError(f"Exponent must be a safe integer, got {js_number(exponent)}")
    if exponent >= 0:
        # Powers of coprime integers stay coprime.
        return _canonical(self.numerator**exponent, self.denominator**exponent)
    if self.numerator == 0:
        return None
    numerator = self.numerator**-exponent
    denominator = self.denominator**-exponent
    if numerator < 0:
        return _canonical(-denominator, -numerator)
    return _canonical(denominator, numerator)

pow_unsafe

pow_unsafe(exponent) -> Rational

pow; raises ZeroDivisionError for zero to a negative power.

ParameterTypeDescription
exponentint

Returns Rational

def pow_unsafe(self, exponent: int) -> Rational:
    """``pow``; raises ``ZeroDivisionError`` for zero to a negative power."""
    out = self.pow(exponent)
    if out is None:
        raise ZeroDivisionError("Division by zero")
    return out

negate

negate() -> Rational

Returns Rational

def negate(self) -> Rational:
    return _canonical(-self.numerator, self.denominator)

abs

abs() -> Rational

Returns Rational

def abs(self) -> Rational:
    return self.negate() if self.numerator < 0 else self

compare

compare(that) -> Literal[-1, 0, 1]

Effect's Order: -1, 0 or 1.

ParameterTypeDescription
thatRational

Returns Literal[-1, 0, 1]

def compare(self, that: Rational) -> Literal[-1, 0, 1]:
    """Effect's ``Order``: ``-1``, ``0`` or ``1``."""
    # Denominators are positive, so cross-multiplying keeps the order.
    left = self.numerator * that.denominator
    right = that.numerator * self.denominator
    return -1 if left < right else 1 if left > right else 0

between

between(*, minimum, maximum) -> bool

minimum <= self <= maximum.

ParameterTypeDescription
minimumRational
maximumRational

Returns bool

def between(self, *, minimum: Rational, maximum: Rational) -> bool:
    """``minimum <= self <= maximum``."""
    return minimum <= self <= maximum

clamp

clamp(*, minimum, maximum) -> Rational

self held within minimum and maximum.

ParameterTypeDescription
minimumRational
maximumRational

Returns Rational

def clamp(self, *, minimum: Rational, maximum: Rational) -> Rational:
    """``self`` held within ``minimum`` and ``maximum``."""
    return min(max(self, minimum), maximum)