Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: respect both mulitple_of and minimum/maximum constraints #505

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Replace math.ulp with manually implemented code.
Python 3.8 doesn't have the ulp() function, so we need to manually
compute an increment ourselves.
  • Loading branch information
richardxia committed Mar 19, 2024
commit 08db6fa61595f24d603963510099779e57892314
10 changes: 7 additions & 3 deletions polyfactory/value_generators/constrained_numbers.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from decimal import Decimal
from math import ceil, floor, ulp
from math import ceil, floor, frexp
from sys import float_info
from typing import TYPE_CHECKING, Protocol, TypeVar, cast

Expand Down Expand Up @@ -131,8 +131,12 @@ def get_increment(value: T, t_type: type[T]) -> T:
# to not be rounded away, but when ``value`` small in magnitude, we need to prevent the
# incerement from vanishing. ``float_info.epsilon`` is defined as the smallest delta that
# can be represented between 1.0 and the next largest number, but it's not sufficient for
# larger values. ``ulp(x)`` will return smallest delta that can be added to ``x``.
return cast("T", max(ulp(value), float_info.epsilon)) # type: ignore[redundant-cast]
# larger values. We instead open up the floating-point representation to grab the exponent
# and calculate our own increment. This can be replaced with ``math.ulp`` in Python 3.9 and
# later.
_, exp = frexp(value)
increment = float_info.radix ** (exp - float_info.mant_dig + 1)
return cast("T", max(increment, float_info.epsilon))
if t_type == Decimal:
return cast("T", Decimal("0.001")) # type: ignore[redundant-cast]

Expand Down
Loading