Public
Edited
Jan 28
1 fork
1 star
Insert cell
Insert cell
Insert cell
Insert cell
ti = import("https://cdn.jsdelivr.net/npm/taichi.js/+esm")
Insert cell
Insert cell
Insert cell
Insert cell
fractal = async () => {
await ti.init();

let n = 320;
let pixels = ti.Vector.field(4, ti.f32, [2 * n, n]);

let complex_sqr = (z) => {
return [z[0] ** 2 - z[1] ** 2, z[1] * z[0] * 2];
};

ti.addToKernelScope({ pixels, n, complex_sqr });

let kernel = ti.kernel((t) => {
for (let I of ti.ndrange(n * 2, n)) {
let i = I[0];
let j = I[1];
let c = [-0.8, Math.cos(t) * 0.2];
let z = [i / n - 1, j / n - 0.5] * 2;
let iterations = 0;
while (z.norm() < 20 && iterations < 50) {
z = complex_sqr(z) + c;
iterations = iterations + 1;
}
pixels[(i, j)] = 1 - iterations * 0.02;
pixels[(i, j)][3] = 1;
}
});

let htmlCanvas = document.getElementById("canvas1");
htmlCanvas.width = 2 * n;
htmlCanvas.height = n;
let canvas = new ti.Canvas(htmlCanvas);

let i = 0;
async function frame() {
kernel(i * 0.05);
i = i + 1;
canvas.setImage(pixels);
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
}
Insert cell
Insert cell
Insert cell
Insert cell
computeMatrixMultiplication = async (matrixA, matrixB) => {
await ti.init();

const n = matrixA.length;
const m = matrixA[0].length;
const p = matrixB[0].length;

const A = ti.field(ti.f32, [n, m]);
const B = ti.field(ti.f32, [m, p]);
const C = ti.field(ti.f32, [n, p]);

await A.fromArray(matrixA);
await B.fromArray(matrixB);

ti.addToKernelScope({ A, B, C, n, m, p });

const matrixMultiply = ti.kernel(() => {
for (const I of ti.ndrange(n, p)) {
const i = I[0];
const j = I[1];
const sum = ti.f32(0.0);
for (const k of ti.range(m)) {
sum = sum + A[(i, k)] * B[(k, j)];
}
C[(i, j)] = sum;
}
});

await matrixMultiply();
return C.toArray();
}
Insert cell
Insert cell
m1 = [
[1, 2, 3, 4],
[3, 4, 5, 6],
[5, 6, 7, 8]
]
Insert cell
m2 = [
[5, 6, 7],
[7, 8, 9],
[9, 10, 11],
[11, 12, 12]
]
Insert cell
Insert cell
matRes = await computeMatrixMultiplication(m1, m2)
Insert cell
Insert cell
areMatricesEqual(
matRes,
multiplyMatricesCpu(m1, m2)
)
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more