typestar

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

  1. Scaling by 100.0 moves dollars into cents while still in float.
  2. .cast[DType.int32]() truncates each lane toward zero.
  3. Casting back to float64 and dividing recovers the original prices.

Keywords and builtins used here

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.

Type this snippet

Step 5 of 6 in SIMD, step 10 of 22 in Parameters & SIMD.

← Previous Next →