Rust RangeInclusive< f32>步长按一定值

5vf7fwbs  于 2023-04-12  发布在  其他
关注(0)|答案(1)|浏览(152)

以下为循环:

let min_pos = 0.0;
let max_pos = 10.0;
for x in (min_pos..=max_pos).step_by(0.5) { /*...*/ }

在Rust 1.68中出现编译错误:

Checking main v0.1.0 (xxx)
error[E0599]: the method `step_by` exists for struct `RangeInclusive<{float}>`, but its trait bounds were not satisfied                                                                                                  
   --> src/main.rs:5:34
    |
5   |     for x in (min_pos..=max_pos).step_by(0.5) { /*...*/ }
    |                                  ^^^^^^^ method cannot be called on `RangeInclusive<{float}>` due to unsatisfied trait bounds
    |
    |
341 | pub struct RangeInclusive<Idx> {
    | ------------------------------ doesn't satisfy `RangeInclusive<{float}>: Iterator`
    |
    = note: the following trait bounds were not satisfied:
            `{float}: Step`
            which is required by `RangeInclusive<{float}>: Iterator`
            `RangeInclusive<{float}>: Iterator`
            which is required by `&mut RangeInclusive<{float}>: Iterator`

我希望step_by函数对f32和i32都可用,在那里没有问题。
为什么没有?

tcbh2hod

tcbh2hod1#

我希望step_by函数对f32和i32都可用,在那里没有问题。
为什么?
整数数学是精确数学,如果我从0开始,加1三次,我得到3。
另一方面,浮点数数学是近似数学,这可能会导致令人惊讶的结果。如果我从0开始,将1/33加33次,我得到的不是1而是0.9999995。
这种累积的不精确性对于循环结构来说是相当有问题的,这意味着根据N的值,当从0到1循环1 / N时,循环可能执行N次或N+1次。
为了保护你自己,Step trait因此没有为浮点实现。

相关问题