Files
simul/simul-lattice/examples/random_walk_1d.rs
Myeongseon Choi 88eb05ae94
All checks were successful
CI / Format (push) Successful in 1m9s
CI / Clippy (push) Successful in 2m27s
CI / Test (push) Successful in 2m42s
Add 1D random walk dynamics and example
Implement RandomWalk1D dynamics for lattice-based
simulations and provide an example that demonstrates
diffusive scaling. Move prelude into lib.rs for simpler
module organization. Use () for lattice momentum since
discrete walks don't have meaningful momenta.
2026-05-05 19:28:06 +09:00

48 lines
1.4 KiB
Rust

//! Example: 1D simple random walk
//!
//! Runs N_TRIAL independent walks of TIME steps each, then verifies the
//! diffusive scaling: for a 1D simple random walk, <x(t)> = 0 and <x^2(t)> = t.
use nalgebra::SVector;
use rand::{SeedableRng, rngs::StdRng};
use simul_core::dynamics::Dynamics;
use simul_core::state::SystemState;
use simul_lattice::prelude::*;
fn main() -> Result<(), Box<dyn std::error::Error>> {
const N_TRIAL: usize = 10000;
const TIME: usize = 1000;
let mut rng = StdRng::seed_from_u64(42);
let dynamics = RandomWalk1D;
let mut sum_x = 0.0_f64;
let mut sum_x2 = 0.0_f64;
for _ in 0..N_TRIAL {
let mut state: SystemState<Lattice<1>> = SystemState::new();
state.positions.push(SVector::<i32, 1>::zeros());
for _ in 0..TIME {
dynamics.step(&mut state, &mut rng);
}
let x = state.positions[0][0] as f64;
sum_x += x;
sum_x2 += x * x;
}
let mean = sum_x / N_TRIAL as f64;
let var = sum_x2 / N_TRIAL as f64;
println!("RandomWalk1D - 1D simple random walk");
println!("=====================================");
println!(" Trials : {}", N_TRIAL);
println!(" Steps / trial : {}", TIME);
println!();
println!(" <x> = {:>8.3} (expected ~ 0)", mean);
println!(" <x^2> = {:>8.3} (expected ~ {})", var, TIME);
Ok(())
}