Task 3 of 5

From For-Loop to Formula

Here's the payoff of the thread index. On the CPU you'd sample a sine wave like this:

for (let i = 0; i < 64; i++) {
  wave[i] = Math.sin(i / 64 * 2 * Math.PI);
}

On the GPU, the loop disappears — the 64 iterations become 64 threads, and the loop variable i becomes this.thread.x. The body of the loop is your kernel body, unchanged. (Math.sin and Math.PI work inside kernels, along with most of Math.)

same body, new address — the loop unrolls into threads
Goal: sample one full sine cycle across 64 threads — thread x returns Math.sin(x / 64 * 2 * Math.PI).

Requirements

Hint 1 — the translation rule

Take the CPU loop body, delete the loop, and substitute this.thread.x for i. That mechanical rewrite is how most for-loops become kernels.

Hint 2 — the body
return Math.sin(this.thread.x / 64 * 2 * Math.PI);

Same idea elsewhere

This loop-body-becomes-kernel-body rewrite is called an embarrassingly parallel map, and it's the bread and butter of GPGPU: the same move turns a pixel loop into a Metal fragment shader, a physics update into a CUDA kernel, or an array transform into a WebGPU compute pass.

All tasks in Hello, Kernel

  1. Your First Kernel
  2. Who Am I? this.thread.x
  3. From For-Loop to Formula
  4. A Second Dimension: this.thread.y
  5. Pass Something In

This page is an interactive exercise — the editor, the GPU runner and your saved progress need JavaScript. The text above is the full brief.