-
Notifications
You must be signed in to change notification settings - Fork 52
Open
Labels
topic: Complex Data TypesComplex number data types.Complex number data types.topic: Type PromotionType promotion.Type promotion.
Milestone
Description
I would like to compute float
and uint
, using array-api. However, I am not sure what is the best way to implement it. Following the type promotion rules
def f(x: xp.array) -> xp.array:
return x * xp.array(1j, dtype=xp.complex64 if x.dtype == xp.float32 else xp.complex128)
def g(x: xp.array) -> xp.array:
return x - xp.array(1, dtype=xp.int16 if x.dtype == xp.uint8 else xp.int32 if x.dtype == xp.uint16 else xp.int64)
This seems too redundant. What is the proper way to do this?
Metadata
Metadata
Assignees
Labels
topic: Complex Data TypesComplex number data types.Complex number data types.topic: Type PromotionType promotion.Type promotion.
Type
Projects
Milestone
Relationships
Development
Select code repository
Activity
lucascolley commentedon Nov 25, 2024
see gh-841
asmeurer commentedon Nov 26, 2024
That issue covers the complex case. Once it is fixed,
x*1j
should work as you would expect whenx
has a floating-point dtype.For the second cast, the standard works like this:
The difference is your example would make the resulting type
int16
. The type promotion rules for scalars says that Python scalars first cast to the type of the array, so<uint8 array> - <python int>
will always produces a uint8 array. In this particular case, the result is not actually defined (see the note at https://data-apis.org/array-api/latest/API_specification/generated/array_api.array.__neg__.html#neg, together with the note sayingx - y == x + (-y)
at https://data-apis.org/array-api/latest/API_specification/generated/array_api.array.__sub__.html#sub; small nit,__sub__
should probably just state this fact more directly, since it's only undefined whenx - y
is negative).The rule that scalars always cast to the same dtype as the array is not something that should change, so you'd want some other way to spell
y - 1
so that it upcasts to a signed dtype.I think the
astype
suggestion in #841 (comment) would be the cleanest way to do this. If it were implemented, you could writewhere
xp.astype(<uint8>, 'signed')
would return anint16
array (and would error for uint64, but that's always a tricky dtype to deal with in the context of type promotion).The astype improvements idea should be split out into its own issue. I doubt it would be implemented for the 2024 standard release, since it hasn't even been fleshed out yet (though it's not impossible). The complex-scalar-to-float-array issue will definitely be fixed for 2024.
lucascolley commentedon Nov 26, 2024
gh-848 😉 (are there complexities which I haven't thought about? A review would be appreciated!)
astype
#848