rand_gpu_wasm 1.0.0

Random number generation compatible with RustGPU and WASM.
Documentation

rand_gpu_wasm

GitHub Workflow Status Crates.io Docs.rs

Random number generation compatible with RustGPU and WASM.

This crate was originally created as part of a small project aimed to use RustGPU alongside wgpu to create a simple physics simulation that runs on the web with GPU acceleration. The project is available on GitHub, with a web live demo (needs a WebGPU enabled browser).

Usage

To use rand_gpu_wasm in your Rust project, simply add it as a dependency in your Cargo.toml:

[dependencies]
rand_gpu_wasm = "1"

Available random number generators

The only currently available random number generator is Philox4x32, which is the 32 bits variant of the Philox algorithm coming from Random123.

Example

// Use random numbers to approximate the value of pi.

// Import The `GPURng` Trait and the Philox4x32 rng.
use rand_gpu_wasm::{GPURng, philox::Philox4x32};

// Create independent random number generators.
let seed = 42;
let mut rands = [Philox4x32::new(seed, 0), Philox4x32::new(seed, 1)];

// Sample many points in the unit square, which is the top right square of a unit circle.
let n = 10000;
let mut inside_circle = 0;
for _ in 0..n {
    // Sample 2 coordinates. This can be done in parallel if needed.
    let x = rands[0].next_uniform();
    let y = rands[1].next_uniform();

    // Increment the count if the sampled coordinates are inside the unit circle.
    if x * x + y * y <= 1.0 {
        inside_circle += 1;
    }
}
// Compute the area inside the top right part of the unit circle by dividing
// the number of points found inside with the total number of points sampled.
let area = inside_circle as f32 / n as f32;

// The total area of the unit circle is pi, so the top right area is pi/4.
let pi = area * 4.0;

// Verify that the approximate value is close to the exact value
use core::f32::consts::PI;
assert!((pi - PI).abs() / PI < (n as f32).sqrt(), "{pi}")