# rand_gpu_wasm
[](https://github.com/xayon40-12/rand_gpu_wasm/actions)
[](https://crates.io/crates/rand_gpu_wasm)
[](https://docs.rs/rand_gpu_wasm)
Random number generation compatible with [RustGPU](https://rust-gpu.github.io) and WASM.
This crate was originally created as part of a small project aimed to use [RustGPU](https://rust-gpu.github.io) alongside [wgpu](https://github.com/gfx-rs/wgpu) to create a simple physics simulation that runs on the web with GPU acceleration. The project is available on [GitHub](https://github.com/xayon40-12/phase), with a [web live demo](https://xayon40-12.github.io/phase) (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`:
```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](https://random123.com).
### Example
```rust
// 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}")
```