从特性到特性以及将usize转换为f64

Sid*_*ord 3 type-conversion rust

我一直试图以一种非常通用的方式编写一些Rust代码,而没有明确指定类型。但是,我到达了需要将a转换usize为a的位置f64,但这不起作用。大概f64没有足够的精度来保存任意usize值。在夜间频道上进行编译时,出现错误消息:error: the trait `core::convert::From<usize>` is not implemented for the type `f64` [E0277]

那么,如果我想编写尽可能通用的代码,那有什么选择呢?显然,我应该使用可能会失败的特征(与Into或不同From)。已经有那样的东西了吗?是否有通过实施转换的特征as

这是下面的代码。

#![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);
}
Run Code Online (Sandbox Code Playgroud)

小智 9

您可以使用as

let num: f64 = 12 as f64 ;
Run Code Online (Sandbox Code Playgroud)

  • 这不适用于通用的“as T”转换,这就是问题所在。 (5认同)

DK.*_*DK. 5

问题是那个整数?浮点类型的大小等于或小于整数的浮点转换不能保留所有值。那usizef64在64位上失去精度。

这些类型的转换基本上是conv板条箱的存在理由,它定义了类型(主要是内置数字类型)之间的许多易犯错误的转换。(截至10分钟前)包括isize/ usizef32/ f64

使用conv,您可以执行以下操作:

use conv::prelude::*;

...

where T: ValueFrom<usize> + ...

...
ans[k] = ans[k - 1] / (k + 1).value_as::<T>().unwrap();
...
Run Code Online (Sandbox Code Playgroud)

免责声明:我是有关箱子的作者。

  • *(截至 10 分钟前)* =&gt; 谈论快速解决! (4认同)
  • 板条箱“num_traits”也将执行此操作。 (3认同)