Created
August 27, 2017 06:23
-
-
Save rinx/a9d31282f90903b859aed26f0f676515 to your computer and use it in GitHub Desktop.
a simple monte carlo 1d radiative transfer code in Rust
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
extern crate rand; | |
use std::f64; | |
use rand::Rng; | |
struct MCInput { | |
np: u64, | |
tau: f64, | |
sal: f64, | |
omg: f64, | |
} | |
impl MCInput { | |
fn new(np: u64, tau: f64, sal: f64, omg: f64) -> MCInput { | |
MCInput {np: np, tau: tau, sal: sal, omg: omg} | |
} | |
} | |
fn main() { | |
let np = 1000000; | |
let tau = 1.0; | |
let sal = 0.5; | |
let omg = 1.0; | |
let mc_input = MCInput::new(np, tau, sal, omg); | |
let (reflectance, transmittance)= mc_world(mc_input); | |
println!("reflectance: {}, transmittance: {}", reflectance, transmittance); | |
} | |
fn rnd_uniform() -> f64 { | |
rand::thread_rng().gen_range(0.0, 1.0) | |
} | |
fn mc_world(mc_input: MCInput) -> (f64, f64) { | |
let np = mc_input.np; | |
let f64np = np as f64; | |
let tau = mc_input.tau; | |
let sal = mc_input.sal; | |
let omg = mc_input.omg; | |
let zu = tau; | |
let zb = 0.0; | |
let mut sumr = 0.0; | |
let mut sumt = 0.0; | |
for _i in 1..np { | |
let mut w = 1.0; | |
let mut z = zu; | |
let mut dir = -1.0; | |
while z <= zu { | |
let path = - f64::ln(rnd_uniform()); | |
z = zu + dir * path; | |
if z <= zb { | |
z = zb; | |
dir = 1.0; | |
sumt = sumt + w; | |
w = w * sal; | |
} else if z >= zu { | |
sumr = sumr + w; | |
} else { | |
if rnd_uniform() <= 0.5 { | |
dir = 1.0 * dir; | |
} else { | |
dir = -1.0 * dir; | |
} | |
w = w * omg; | |
} | |
} | |
} | |
(sumr / f64np, sumt / f64np) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment