Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
8 changes: 7 additions & 1 deletion mlx/ops.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3165,8 +3165,14 @@ array floor_divide(

auto inputs = broadcast_arrays({astype(a, dtype, s), astype(b, dtype, s)}, s);
auto shape = inputs[0].shape();
return array(
auto quotient = array(
shape, dtype, std::make_shared<Divide>(to_stream(s)), std::move(inputs));
auto rem = remainder(a, b, s);
auto zero = array(0, dtype);
auto step = logical_and(
not_equal(rem, zero, s),
not_equal(less(a, zero, s), less(b, zero, s), s));
return subtract(quotient, astype(step, dtype, s), s);
}

array remainder(const array& a, const array& b, StreamOrDevice s /* = {} */) {
Expand Down
25 changes: 25 additions & 0 deletions python/tests/test_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,31 @@ def test_divide(self):
self.assertEqual(z.dtype, mx.int32)
self.assertEqual(z.item(), 2)

def test_floor_divide(self):
a = [4, 5, -1, -6]
b = [-2, 3, 2, -3]

mx_int_float_dtypes = mx.__array_namespace_info__().dtypes(
kind=("signed integer", "real floating")
)
np_int_float_dtypes = np.__array_namespace_info__().dtypes(
kind=("signed integer", "real floating")
)

for kind, dtype in mx_int_float_dtypes.items():
with self.subTest(dtype=dtype):
result = mx.floor_divide(
mx.array(a, dtype=dtype), mx.array(b, dtype=dtype)
)
expected = np.floor_divide(
np.array(a, dtype=np_int_float_dtypes[kind]),
np.array(b, dtype=np_int_float_dtypes[kind]),
)
self.assertEqual(result.tolist(), expected.tolist())

result = mx.array(a, dtype=dtype) // mx.array(b, dtype=dtype)
self.assertEqual(result.tolist(), expected.tolist())

def test_remainder(self):
# Complex is not supported and has to say so rather than quietly
# computing a componentwise remainder, which no other library defines
Expand Down
Loading