Dynamic precision in computation


Hi everyone. I’m trying to write some statistic functions in rust. I want to create a dynamic typing for those computations.

trait Statistic {
  fn mean<Precision: FromNumber + Div>(&self) -> Precision;

The function wil be used like:

(vec![1, 2, 3, 4, 5]).mean::<f32>(); // Will give a single precision mean
(vec![1, 2, 3, 4, 5]).mean::<f64>(); // Will perform a double precision mean

I provide a link to a playground : https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=10c44a5c73df9b8c9726fb949d73187c

The purpose is to let the user to define which precision the computation will use (and also the return type).

Thank’s for help =)


I would use the num crate to generalize over numbers.

It can be used like so.

trait Statistic {
  fn mean<Precision: num::Float>(&self) -> Precision;


modified playground


Thank’s that is exactly what I was looking for :grinning: