Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From and Into traits and conversion of usize to f64

I've been trying to write some Rust code in a very generic way, without specifying the types explicitly. However, I arrived at a point where I need to convert a usize to a f64 and this doesn't work. Presumably, f64 does not have enough precision to hold a an arbitrary usize value. When compiling on the nightly channel I get an error message: error: the trait `core::convert::From<usize>` is not implemented for the type `f64` [E0277].

What is the alternative, then, if I want to write the code as generic as possible? Clearly I should use a trait for conversion which can fail (unlike Into or From). Is there something like that already? Is there a trait for implementing the conversion by as?

Here is the code below.

#![feature(zero_one)]
use std::num::{Zero, One};
use std::ops::{Add, Mul, Div, Neg};
use std::convert::{From, Into};

/// Computes the reciprocal of a polynomial or of a truncation of a
/// series.
///
/// If the input is of length `n`, then this performs `n^2`
/// multiplications.  Therefore the complexity is `n^2` when the type
/// of the entries is bounded, but it can be larger if the type is
/// unbounded, as for BigInt's.
///
fn series_reciprocal<T>(a: &Vec<T>) -> Vec<T>
    where T: Zero + One + Add<Output=T> + Mul<Output=T> +
             Div<Output=T> + Neg<Output=T> + Copy {

    let mut res: Vec<T> = vec![T::zero(); a.len()];
    res[0] = T::one() / a[0];

    for i in 1..a.len() {
        res[i] = a.iter()
                  .skip(1)
                  .zip(res.iter())
                  .map(|(&a, &b)| a * b)
                  .fold(T::zero(), |a, b| a + b) / (-a[0]);
    }
    res
}

/// This computes the ratios `B_n/n!` for a range of values of `n`
/// where `B_n` are the Bernoulli numbers.  We use the formula
///
///    z/(e^z - 1) = \sum_{k=1}^\infty \frac {B_k}{k!} z^k.
///
/// To find the ratios we truncate the series
///
///    (e^z-1)/z = 1 + 1/(2!) z + 1/(3!) z^2 + ...
///
/// to the desired length and then compute the inverse.
///
fn bernoulli_over_factorial<T, U>(n: U) -> Vec<T>
    where
        U: Into<usize> + Copy,
        T: Zero + One + Add<Output=T> + Mul<Output=T> +
           Add<Output=T> + Div<Output=T> + Neg<Output=T> +
           Copy + From<usize> {
    let mut ans: Vec<T> = vec![T::zero(); n.into()];
    ans[0] = T::one();
    for k in 1..n.into() {
        ans[k] = ans[k - 1] / (k + 1).into();
    }
    series_reciprocal(&ans)
}

fn main() {
    let v = vec![1.0f32, 1.0f32];
    let inv = series_reciprocal(&v);
    println!("v = {:?}", v);
    println!("v^-1 = {:?}", inv);
    let bf = bernoulli_over_factorial::<f64,i8>(30i8);
}
like image 996
Sidious Lord Avatar asked Mar 13 '16 19:03

Sidious Lord


2 Answers

The problem is that integer → floating point conversions, where the float type is the same size or smaller than the integer, cannot preserve all values. So usizef64 loses precision on 64-bit.

These sorts of conversions are basically the raison d'être for the conv crate, which defines numerous fallible conversions between types (mostly built-in numeric ones). This (as of 10 minutes ago) includes isize/usizef32/f64.

Using conv, you can do this:

use conv::prelude::*;

...

where T: ValueFrom<usize> + ...

...
ans[k] = ans[k - 1] / (k + 1).value_as::<T>().unwrap();
...

Disclaimer: I am the author of the crate in question.

like image 104
DK. Avatar answered Oct 07 '22 18:10

DK.


You can do it using as:

let num: f64 = 12 as f64 ;
like image 39
Shaurya Avatar answered Oct 07 '22 19:10

Shaurya