mirror of
https://github.com/ml-explore/mlx.git
synced 2025-09-06 16:51:24 +08:00
Added linspace (#181)
* linspace ops support --------- Co-authored-by: Awni Hannun <awni@apple.com>
This commit is contained in:
@@ -1184,6 +1184,32 @@ void init_ops(py::module_& m) {
|
||||
This can lead to unexpected results for example if `start + step`
|
||||
is a fractional value and the `dtype` is integral.
|
||||
)pbdoc");
|
||||
m.def(
|
||||
"linspace",
|
||||
[](Scalar start, Scalar stop, int num, Dtype dtype, StreamOrDevice s) {
|
||||
return linspace(
|
||||
scalar_to_double(start), scalar_to_double(stop), num, dtype, s);
|
||||
},
|
||||
"start"_a,
|
||||
"stop"_a,
|
||||
"num"_a = 50,
|
||||
"dtype"_a = float32,
|
||||
"stream"_a = none,
|
||||
R"pbdoc(
|
||||
linspace(start, stop, num: Optional[int] = 50, dtype: Optional[Dtype] = float32, stream: Union[None, Stream, Device] = None) -> array
|
||||
|
||||
Generate ``num`` evenly spaced numbers over interval ``[start, stop]``.
|
||||
|
||||
Args:
|
||||
start (scalar): Starting value.
|
||||
stop (scalar): Stopping value.
|
||||
num (int, optional): Number of samples, defaults to ``50``.
|
||||
dtype (Dtype, optional): Specifies the data type of the output,
|
||||
default to ``float32``.
|
||||
|
||||
Returns:
|
||||
array: The range of values.
|
||||
)pbdoc");
|
||||
m.def(
|
||||
"take",
|
||||
[](const array& a,
|
||||
|
@@ -1491,6 +1491,27 @@ class TestOps(mlx_tests.MLXTestCase):
|
||||
clipped = mx.clip(mx.array(a), mx.array(mins), mx.array(maxs))
|
||||
self.assertTrue(np.array_equal(clipped, expected))
|
||||
|
||||
def test_linspace(self):
|
||||
# Test default num = 50
|
||||
a = mx.linspace(0, 1)
|
||||
expected = mx.array(np.linspace(0, 1))
|
||||
self.assertEqualArray(a, expected)
|
||||
|
||||
# Test int32 dtype
|
||||
b = mx.linspace(0, 10, 5, mx.int64)
|
||||
expected = mx.array(np.linspace(0, 10, 5, dtype=int))
|
||||
self.assertEqualArray(b, expected)
|
||||
|
||||
# Test negative sequence with float start and stop
|
||||
c = mx.linspace(-2.7, -0.7, 7)
|
||||
expected = mx.array(np.linspace(-2.7, -0.7, 7))
|
||||
self.assertEqualArray(c, expected)
|
||||
|
||||
# Test irrational step size of 1/9
|
||||
d = mx.linspace(0, 1, 10)
|
||||
expected = mx.array(np.linspace(0, 1, 10))
|
||||
self.assertEqualArray(d, expected)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
Reference in New Issue
Block a user