2.2_Numba_lab_solution
Numba Lab
Now it's your turn!
Your challenge is to implement Fizz Buzz in CUDA Python with numba and calculate all instances of Fizz, Buzz and Fizz Buzz for the numbers between 1 and 50_000_000.
import numpy as np
from numba import cuda1. Create the input data array. Try using np.arange.
data = np.arange(1, 50_000_000)
data2. Create the output data array.
output = np.zeros_like(data)
output3. Calculate the number of threads and blocks.
import math
threads = 128
blocks = math.ceil(data.shape[0] / threads)4. Create the kernel. Tip: Our output array must be numeric so try using the values 1, 2 and 3 to represent Fizz, Buzz and Fizz Buzz.
@cuda.jit
def fizz_buzz(input_array, output_array):
i = cuda.grid(1)
n = input_array[i]
if n % 3 == 0:
output_array[i] = 1 # Fizz
if n % 5 == 0:
output_array[i] = 2 # Buzz
if n % 15 == 0:
output_array[i] = 3 # Fizz Buzz5. Run our kernel.
%%time
fizz_buzz[blocks, threads](data, output)
output[:12]Extra Credit 6. Calculate the highest instance of Fizz.
idx = np.where(output == 1)[0][-1]
data[idx]