0

I am trying to run following rust source file as script using cargo-script:

// cargo-deps: statistical

extern crate statistical;
use statistical::*;
fn main() {
    let alist = [10, 20, 30, 40, 50];
    println!("mean of list: {}", mean(&alist)); // not working
}

However, I am getting following error:

$ cargo script mystats.rs 
    Updating crates.io index
   Compiling mystats v0.1.0 (/home/abcde/.cargo/script-cache/file-mystats-6e38bab8b3f0569c)
error[E0277]: the trait bound `{integer}: num_traits::float::Float` is not satisfied
 --> mystats.rs:7:31
  |
7 |     println!("mean of list: {}", mean(&alist));  // not working
  |                                  ^^^^ the trait `num_traits::float::Float` is not implemented for `{integer}`
  |
  = help: the following implementations were found:
            <f32 as num_traits::float::Float>
            <f64 as num_traits::float::Float>
  = note: required by `statistical::mean`

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: Could not compile `mystats`.

To learn more, run the command again with --verbose.
internal error: cargo failed with status 101

How can this integer/float problem be solved?

1
  • Tbh the function signature of mean is a little bit quirky, because I see no reason why they can't accept something like fn mean<I: Float>(p: impl Iterator<Item = I>) -> I; and you were not forced to pass a slice Commented Apr 26, 2019 at 8:26

1 Answer 1

1

The problem is that the mean function wants to return the same type as the one in the slice. If it allowed integers, you could be able to compute the mean of [0, 1] and it would return 0 (1 / 2 as an integer). That's why statistical forces you to use floatting types.

The following works on my machine

// cargo-deps: statistical
extern crate statistical;
use statistical::*;

fn main() {
    let alist = [10, 20, 30, 40, 50];
    let alist_f64: Vec<f64> = alist.iter().map(|x| f64::from(*x)).collect();
    println!("mean of list: {}", mean(&alist_f64));
}

It prints this

mean of list: 30

Note that the collect function will make a copy of the array. There would be a better way if the mean function would take an iterator as parameter but it doesn't seem to be the case.

Sign up to request clarification or add additional context in comments.

2 Comments

<pedant on>It's usually better to do f64::from (*x) instead of *x as f64.
Yes. You could refer to the error message "the trait num_traits::float::Float is not implemented for {integer}", and explain that Float is obviously not implemented for an integer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.