From a2cadb8218a6b350557a1a06954b65834e6cd446 Mon Sep 17 00:00:00 2001 From: Awni Hannun Date: Thu, 15 May 2025 18:17:50 -0700 Subject: [PATCH] real and imag properties (#2189) --- docs/src/python/array.rst | 2 ++ python/src/array.cpp | 12 ++++++++++++ python/tests/test_array.py | 9 +++++++++ 3 files changed, 23 insertions(+) diff --git a/docs/src/python/array.rst b/docs/src/python/array.rst index 7e1c3339d..e68524d5a 100644 --- a/docs/src/python/array.rst +++ b/docs/src/python/array.rst @@ -19,6 +19,8 @@ Array array.ndim array.shape array.size + array.real + array.imag array.abs array.all array.any diff --git a/python/src/array.cpp b/python/src/array.cpp index 5f8dbe021..5ba0aaedc 100644 --- a/python/src/array.cpp +++ b/python/src/array.cpp @@ -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, diff --git a/python/tests/test_array.py b/python/tests/test_array.py index 792e666d6..e63da17df 100644 --- a/python/tests/test_array.py +++ b/python/tests/test_array.py @@ -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()