Skip to content

Conversation

@forfudan
Copy link
Collaborator

@forfudan forfudan commented Feb 7, 2025

This PR aims to improve the behaviors of 0-dimensional array (numojo scalar). Note that a.item(0) or a[Item(0)] is always preferred because the behavior is more determined, but we also allow some basic operations on 0darray to make users' life easier.

0-dimensional array cannot be constructed by users but can be obtained by array indexing and slicing. Printing this variable gives the scalar and a note that it is an 0darray instead of a mojo scalar. It is similar to numpy in that a[0] returns a numpy scalar and a.item(0) returns a Python scalar. For example,

>>> var a = nm.random.arange[f16](0, 3, 0.12)
>>> print(a[1])
0.11999512  (0darray[f16])
>>> print(a.item(1))
0.11999512
>>> var c = nm.array[f16]("[[1,2], [3,4]]")
>>> print(c[1, 1])
4.0  (0darray[f16])

0-dimensional array can be unpacked to get the corresponding mojo scalar either by [] or by item(). For example,

>>> var a = nm.random.arange[f16](0, 3, 0.12)
>>> var b = a[1]
>>> print(b)
0.11999512  (0darray[f16])
>>> print(b[])  # Unpack using []
0.11999512
>>> print(b.item())  # Unpack using item()
0.11999512

0-dimensional array can be used in arithmetic operations, just like a scalar.

>>> var a = nm.random.arange[f16](0, 3, 0.12)
>>> var b = a[1]
>>> var c = nm.array[f16]("[[1,2], [3,4]]")
>>> var d = c[1, 1]
>>> print(b - d)  # Arithmetic operations between two 0darrays
-3.8808594  (0darray[f16])
>>> print(b[] - d[])  # Arithmetic operations after unpacking
-3.8808594
>>> print(b < d)  # Comparison between 0darray and 0darray
True  (0darray[boolean])
>>>print(b == d[])  # Comparison between 0darray and unpacked 0darray
False  (0darray[boolean])

@shivasankarka shivasankarka merged commit 15b01cb into Mojo-Numerics-and-Algorithms-group:pre-0.6 Feb 8, 2025
2 checks passed
@forfudan forfudan deleted the ndarray branch February 8, 2025 13:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants