Skip to content

Commit

Permalink
implement intbounds for FloorDivide
Browse files Browse the repository at this point in the history
  • Loading branch information
joostvanzwieten committed Feb 29, 2024
1 parent 0085a8c commit 1a10071
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
19 changes: 19 additions & 0 deletions nutils/evaluable.py
Original file line number Diff line number Diff line change
Expand Up @@ -2261,6 +2261,25 @@ def return_type(dividend, divisor):
raise ValueError(f'The boolean floor division is not supported.')
return dividend

def _intbounds_impl(self):
lower, upper = self.args[0]._intbounds
divisor_lower, divisor_upper = self.args[1]._intbounds
if divisor_upper < 0:
divisor_lower, divisor_upper = -divisor_upper, -divisor_lower
lower, upper = -upper, -lower
elif divisor_lower <= 0:
# The divisor range includes zero.
return float('-inf'), float('inf')
# `divisor_lower` is always finite and positive. `divisor_upper` may be
# `float('inf')` in which case the floordiv of a finite `lower` or
# `upper` with `divisor_upper` gives a float `0.0` or `-1.0`. To
# prevent the float, we bound `divisor_upper` by the dividend.
if isinstance(lower, int):
lower //= divisor_lower if lower <= 0 else min(lower + 1, divisor_upper)
if isinstance(upper, int):
upper //= divisor_lower if upper >= 0 else min(1 - upper, divisor_upper)
return lower, upper


class Absolute(Pointwise):
evalf = staticmethod(numpy.absolute)
Expand Down
7 changes: 7 additions & 0 deletions tests/test_evaluable.py
Original file line number Diff line number Diff line change
Expand Up @@ -734,6 +734,13 @@ def test_mod_wrap_positive(self):
def test_mod_negative_divisor(self):
self.assertEqual(evaluable.Mod(evaluable.Argument('d', (evaluable.constant(2),), int), self.R(-3, [2]))._intbounds, (float('-inf'), float('inf')))

def test_floordiv(self):
self.assertBounds(evaluable.FloorDivide(evaluable.insertaxis(self.R(2, [9]), 1, evaluable.constant(2)), evaluable.insertaxis(self.R(3, [2]), 0, evaluable.constant(9))))
self.assertBounds(evaluable.FloorDivide(evaluable.insertaxis(self.R(-12, [9]), 1, evaluable.constant(2)), evaluable.insertaxis(self.R(3, [2]), 0, evaluable.constant(9))))
self.assertBounds(evaluable.FloorDivide(evaluable.insertaxis(self.R(-15, [9]), 1, evaluable.constant(2)), evaluable.insertaxis(self.R(-3, [2]), 0, evaluable.constant(9))))
self.assertBounds(evaluable.FloorDivide(evaluable.insertaxis(self.R(-4, [9]), 1, evaluable.constant(2)), evaluable.insertaxis(self.R(8, [2]), 0, evaluable.constant(9))))
self.assertEqual(evaluable.FloorDivide(self.S('dividend', 2, 4), self.S('divisor', float('-inf'), float('inf')))._intbounds, (float('-inf'), float('inf')))

def test_sign(self):
for i in range(-2, 3):
for j in range(i, 3):
Expand Down

0 comments on commit 1a10071

Please sign in to comment.