将Rational64向下舍入到下一个分数的多个而没有溢出?

时间:2018-02-10 17:46:07

标签: rust integer overflow rational-number

我使用num-rational crate的Rational64类型将数字表示为带符号的64位整数的比率。我试图将一个数字向下舍入到另一个数字的下一个数字,当我以两种显而易见的方式中的任何一种方式执行时,我都会遇到整数溢出问题。请注意,这两个数字可能都是分数。

归一化为整数

extern crate num_rational;
extern crate num_traits;

use num_rational::Rational64;
use num_traits::identities::Zero;

fn round(mut n: Rational64, increment: Rational64) -> Rational64 {
    let rem = n % increment;
    if !rem.is_zero() {
        // normalize to a multiple of the increment, round down
        // to the next integer, and then undo the normalization
        n = (n * increment.recip()).trunc() * increment;
    }
    n
}

fn main() {
    let a = Rational64::new(10_000_676_909_441, 8_872_044_800_000_000);
    let b = Rational64::new(1, 1_000_000);
    let c = round(a, b);
    println!("{}", c);
}

playground

减去余数

extern crate num_rational;
extern crate num_traits;

use num_rational::Rational64;
use num_traits::identities::Zero;

fn round(mut n: Rational64, increment: Rational64) -> Rational64 {
    let rem = n % increment;
    if !rem.is_zero() {
        n -= rem;
    }
    n
}

fn main() {
    let a = Rational64::new(10_000_676_909_441, 8_872_044_800_000_000);
    let b = Rational64::new(1, 1_000_000);
    let c = round(a, b);
    println!("{}", c);
}

playground

有没有办法让n向下舍入到increment的倍数,这样整数溢出的可能性就会降低?如果我必须提取分子和分母(两个Rust i64类型)并直接对它们进行数学运算,那就没问题。

0 个答案:

没有答案