Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created April 7, 2026 10:56
Show Gist options
  • Select an option

  • Save rust-play/691e179a9f50acebbc6b4767a0cb8689 to your computer and use it in GitHub Desktop.

Select an option

Save rust-play/691e179a9f50acebbc6b4767a0cb8689 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
// Cargo.toml dependencies:
// rand = "0.9.2"
// num-traits = "0.2"
// ndarray = "0.16.1"
use std::f64::consts::PI;
use ndarray::Array1;
/// Represents a Quantum Harmonic Oscillator
struct HarmonicOscillator {
mass: f64,
omega: f64,
hbar: f64,
}
impl HarmonicOscillator {
fn new(mass: f64, omega: f64, hbar: f64) -> Self {
Self { mass, omega, hbar }
}
/// Calculates the ground state wavefunction psi_0 at position x
/// psi_0(x) = (m*w / (pi*hbar))^1/4 * exp(-m*w*x^2 / (2*hbar))
fn psi_0(&self, x: f64) -> f64 {
let coeff = (self.mass * self.omega / (PI * self.hbar)).powf(0.25);
let exponent = -self.mass * self.omega * x.powi(2) / (2.0 * self.hbar);
coeff * exponent.exp()
}
/// Calculates the probability density |psi_0(x)|^2
fn probability_density(&self, x: f64) -> f64 {
self.psi_0(x).powi(2)
}
}
fn main() {
// Constants (normalized: m = 1, w = 1, hbar = 1)
let osc = HarmonicOscillator::new(1.0, 1.0, 1.0);
// Create space grid from -5.0 to 5.0
let steps = 40;
let x_axis = Array1::linspace(-3.0, 3.0, steps);
println!("--- Quantum Harmonic Oscillator: Ground State Probability Density ---");
println!("{:<10} | {:<10} | {:<20}", "x", "Density", "Visual Distribution");
println!("{}", "-".repeat(50));
for &x in x_axis.iter() {
let density = osc.probability_density(x);
// Scale density for a simple ASCII visualization
let bar_width = (density * 50.0) as usize;
let bar = "*".repeat(bar_width);
println!("{:<10.2} | {:<10.4} | {}", x, density, bar);
}
// Example of integrating specific logic for energy
let energy_0 = 0.5 * osc.hbar * osc.omega;
println!("\nGround State Energy (E0): {:.2} units", energy_0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment