Casting SIMD lanes in Mojo
cast converts every lane to another DType without leaving the vector.
comptime F4 = SIMD[DType.float64, 4]
def main():
var prices = F4(1.9, 2.5, 3.1, 4.8)
var cents = (prices * 100.0).cast[DType.int32]()
print(cents)
print(cents.cast[DType.float64]() / 100.0)
print(prices.cast[DType.int32]())
How it works
- Scaling by
100.0moves dollars into cents while still in float. .cast[DType.int32]()truncates each lane toward zero.- Casting back to
float64and dividing recovers the original prices.
Keywords and builtins used here
DTypeSIMDdefmainprintvar
The run, in numbers
- Lines
- 9
- Characters to type
- 225
- Tokens
- 69
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 59 seconds.
Step 5 of 6 in SIMD, step 10 of 22 in Parameters & SIMD.