Skip to content

Instantly share code, notes, and snippets.

@RandyMcMillan
Forked from rust-play/playground.rs
Last active March 22, 2025 15:18
Show Gist options
  • Save RandyMcMillan/ef0700f9c0f49b2a88d4ffaabba2d593 to your computer and use it in GitHub Desktop.
Save RandyMcMillan/ef0700f9c0f49b2a88d4ffaabba2d593 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::time::{SystemTime, UNIX_EPOCH};
const EPSILON_TWEAK: f64 = f64::EPSILON * /*adjust for granularity*/ 0.00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002;
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BlochVector {
pub x: f64,
pub y: f64,
pub z: f64,
}
impl BlochVector {
pub fn new(x: f64, y: f64, z: f64) -> Self {
assert!(
x * x + y * y + z * z <= (1.0 - f64::EPSILON),
"Bloch vector must be within the unit sphere"
);
BlochVector { x, y, z }
}
pub fn random() -> Self {
let mut rng = Rng::new();
loop {
// for full range
// use -1.0, 1.0
let x = rng.gen_range(-EPSILON_TWEAK, EPSILON_TWEAK);
let y = rng.gen_range(-EPSILON_TWEAK, EPSILON_TWEAK);
let z = rng.gen_range(-EPSILON_TWEAK, EPSILON_TWEAK);
//println!("rng_primer\nx:{}, y:{}, z:{}",x,y,z);
if x * x + y * y + z * z <= 1.0 {
return BlochVector { x, y, z };
}
}
}
}
struct Rng {
state: u64,
}
impl Rng {
fn new() -> Self {
let seed = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos() as u64;
Rng { state: seed }
}
fn next(&mut self) -> u64 {
self.state = self.state.wrapping_mul(6364136223846793005).wrapping_add(1);
self.state
}
fn gen_range(&mut self, low: f64, high: f64) -> f64 {
//16 //16
let rand_val = (self.next() >> 16) as f64 / (1 << 16) as f64;
low + rand_val * (high - low)
}
}
fn main() {
let random_bloch_vector = BlochVector::random();
println!(
"Psuedo-Random Bloch Vector:\nx:{:.1024}\ny:{:.1024}\nz:{:.1024}",
random_bloch_vector.x, random_bloch_vector.y, random_bloch_vector.z
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment