-
-
Save rust-play/39f88220725b7971a82f7b89e1565c60 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 { | |
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 { | |
//11 //53 | |
let rand_val = (self.next() >> 2) as f64 / (1 << 2) 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