Collections
Vec<T>
Vec<T> is an array that grows at runtime, the equivalent of a Java ArrayList. Its elements sit next to each other in memory, which makes it very fast to iterate. You create it empty with Vec::new() or filled with the vec! macro.
fn main() { let mut prices: Vec<f64> = Vec::new(); prices.push(101.5); prices.push(99.8); prices.push(103.2); let tenors = vec![1, 2, 5, 10]; println!("{} prix, {} tenors", prices.len(), tenors.len()); let last = prices.pop(); // Option<f64> : le Vec peut être vide println!("{last:?} retiré, reste {prices:?}");}Two ways to read an element. Indexing v[i] returns the value directly but panics if i is out of bounds. v.get(i) returns an Option: Some(&value) or None. Use indexing when going out of bounds would be a bug, and get when absence is a normal case.
fn main() { let curve = vec![0.010, 0.015, 0.021]; println!("{}", curve[1]); match curve.get(10) { Some(rate) => println!("taux : {rate}"), None => println!("pas de point à cet indice"), } let mut shocked = curve.clone(); for rate in shocked.iter_mut() { *rate *= 2.0; } println!("{shocked:?}"); // [0.02, 0.03, 0.042]}A classic trap: sort() does not work on a Vec<f64>. Floats have no total order because of NaN (NaN is neither smaller nor greater than 1.0). So you sort with sort_by and the f64::total_cmp function, which defines a complete order, NaN included.
fn main() { let mut exposures = vec![450.0, 1_200.0, 0.0, 330.0]; // exposures.sort(); // erreur : the trait `Ord` is not implemented for `f64` exposures.sort_by(f64::total_cmp); println!("{exposures:?}"); let mut ids = vec![42, 7, 19]; ids.sort(); // les entiers ont un ordre total : sort() suffit println!("{ids:?}");}Your turn
Write percentile, which sorts a copy of the values and returns the one at position p (between 0 and 1). This is the basis of PFE, which is a high percentile of exposures.
fn percentile(values: &[f64], p: f64) -> f64 { todo!()} fn main() { let exposures = [0.0, 50.0, 330.0, 120.0, 1_200.0, 80.0, 450.0, 0.0, 60.0, 900.0]; println!("{}", percentile(&exposures, 0.9)); // 1200 println!("{}", percentile(&exposures, 0.5)); // 120}values.to_vec() creates a Vec copied from the slice: you cannot sort a read-only borrowed slice.
fn percentile(values: &[f64], p: f64) -> f64 { let mut sorted = values.to_vec(); sorted.sort_by(f64::total_cmp); let index = (p * sorted.len() as f64) as usize; sorted[index.min(sorted.len() - 1)]} fn main() { let exposures = [0.0, 50.0, 330.0, 120.0, 1_200.0, 80.0, 450.0, 0.0, 60.0, 900.0]; println!("{}", percentile(&exposures, 0.9)); // 1200 println!("{}", percentile(&exposures, 0.5)); // 120}.min(len - 1) guards against p = 1.0, which would produce an index equal to the length. There are several percentile conventions (with or without interpolation); we keep the simplest and will refine it for PFE.