0

How might you write a function to map one numeric range to another in rust?

See this example in C++

i.e:

fn map_range(source: f32, from_a: f32, from_b: f32, to_a: f32, to_b: f32)->f32{
//maps "from" range to "to" range with a given precision
}

dbg!(map_range(1.0, 0.0, 10.0, 0.0, 100.0, 3))
//10.000

ANimator120
  • 2,556
  • 1
  • 20
  • 52

1 Answers1

1

Maybe this is what you are looking for:

use std::f64;
 
fn map_range(from_range: (f64, f64), to_range: (f64, f64), s: f64) -> f64 {
    to_range.0 + (s - from_range.0) * (to_range.1 - to_range.0) / (from_range.1 - from_range.0)
}
 
fn main() {
    let input: Vec<f64> = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0];
    let result = input.into_iter()
        .map(|x| map_range((0.0, 10.0), (-1.0, 0.0), x))
        .collect::<Vec<f64>>();
    print!("{:?}", result);
}

source: https://rosettacode.org/wiki/Map_range#Rust

Leo Lamas
  • 178
  • 9