Language basics
Running project · riskforgeProject: positive exposure
We have every building block for a first version of riskforge. For each simulated scenario, the contract has an MtM. Exposure is the positive part of that MtM: if the value is negative, a counterparty default costs us nothing.
const SCENARIOS: usize = 5; fn exposure(mtm: f64) -> f64 { if mtm > 0.0 { mtm } else { 0.0 }} fn main() { // MtM du contrat dans 5 scénarios de marché, à une date future let mtms: [f64; SCENARIOS] = [1_200.0, -300.0, 450.0, 0.0, -800.0]; let mut total = 0.0; for mtm in mtms { total += exposure(mtm); } let expected_exposure = total / SCENARIOS as f64; println!("EE = {expected_exposure:.2}");}A deliberate limitation: the array has a fixed size and the logic lives in main. In the next module we will pass scenarios by reference to dedicated functions, which will introduce ownership.
Your turn
Add the maximum exposure (the highest exposure across scenarios) and print it next to EE.
fn exposure(mtm: f64) -> f64 { mtm.max(0.0)} fn main() { let mtms = [1_200.0, -300.0, 450.0, 0.0, -800.0]; let mut total = 0.0; for mtm in mtms { total += exposure(mtm); } println!("EE = {:.2}", total / mtms.len() as f64); // exposition maximale ici}A second mut variable initialized to 0.0, updated in the same loop.
fn exposure(mtm: f64) -> f64 { mtm.max(0.0)} fn main() { let mtms = [1_200.0, -300.0, 450.0, 0.0, -800.0]; let mut total = 0.0; let mut max_exposure = 0.0; for mtm in mtms { let e = exposure(mtm); total += e; if e > max_exposure { max_exposure = e; } } println!("EE = {:.2}", total / mtms.len() as f64); println!("max = {max_exposure:.2}");}Exposure is never negative, so 0.0 is a correct starting point. Computing both metrics in the same loop avoids walking the scenarios twice: with 10,000 scenarios, it matters.