real and imag properties (#2189)

This commit is contained in:
Awni Hannun
2025-05-15 18:17:50 -07:00
committed by GitHub
parent c1eb9d05d9
commit a2cadb8218
3 changed files with 23 additions and 0 deletions

View File

@@ -319,6 +319,18 @@ void init_array(nb::module_& m) {
R"pbdoc(
The array's :class:`Dtype`.
)pbdoc")
.def_prop_ro(
"real",
[](const mx::array& a) { return mx::real(a); },
R"pbdoc(
The real part of a complex array.
)pbdoc")
.def_prop_ro(
"imag",
[](const mx::array& a) { return mx::imag(a); },
R"pbdoc(
The imaginary part of a complex array.
)pbdoc")
.def(
"item",
&to_scalar,

View File

@@ -2022,6 +2022,15 @@ class TestArray(mlx_tests.MLXTestCase):
with self.assertRaises(ValueError):
mx.add(y, x)
def test_real_imag(self):
x = mx.array([1.0])
self.assertEqual(x.real.item(), 1.0)
self.assertEqual(x.imag.item(), 0.0)
x = mx.array([1.0 + 1.0j])
self.assertEqual(x.imag.item(), 1.0)
self.assertEqual(x.real.item(), 1.0)
if __name__ == "__main__":
unittest.main()