Rust 'for 循环'(从 C++ 转换)

bli*_*044 3 rust

试图将这个 for 循环从 C++ 转换为 Rust,我很难弄清楚,因为我对 Rust 语法很陌生。

double sinError = 0;
for (float x = -10 * M_PI; x < 10 * M_PI; x += M_PI / 300) {
    double approxResult = sin_approx(x);
    double libmResult = sinf(x);
    sinError = MAX(sinError, fabs(approxResult - libmResult));
}
Run Code Online (Sandbox Code Playgroud)

Alo*_*oso 7

迭代整数

正如@trentcl 已经指出的那样,迭代整数而不是浮点数通常更好,以防止数值错误累加:

use std::f32::consts::PI;

let mut sin_error = 0.0;

for x in (-3000..3000).map(|i| (i as f32) * PI / 300.0) {
    sin_error = todo!();
}
Run Code Online (Sandbox Code Playgroud)

只需替换todo!()为计算 next 的代码sin_error

更实用的方式

use std::f32::consts::PI;

let sin_error = (-3000..3000)
    .map(|i| (i as f32) * PI / 300.0)
    .fold(0.0, |sin_error, x| todo!());
Run Code Online (Sandbox Code Playgroud)

如果您不关心数值错误,或者想要迭代其他内容,这里有一些其他选项:

使用while循环

它不是很好,但可以完成工作!

use std::f32::consts::PI;

let mut sin_error = 0.0;
let mut x = -10.0 * PI;

while (x < 10.0 * PI) {
    sin_error = todo!();
    x += PI / 300.0;
}
Run Code Online (Sandbox Code Playgroud)

创建您的迭代器 successors()

successors()函数创建一个新的迭代器,其中每个后续项都基于前一项计算:

use std::f32::consts::PI;
use std::iter::successors;

let mut sin_error = 0.0;

let iter = successors(Some(-10.0 * PI), |x| Some(x + PI / 300.0));

for x in iter.take_while(|&x| x < 10.0 * PI) {
    sin_error = todo!();
}
Run Code Online (Sandbox Code Playgroud)

更实用的方式

use std::f32::consts::PI;
use std::iter::successors;

let sin_error = successors(Some(-10.0 * PI), |x| Some(x + PI / 300.0))
   .take_while(|&x| x < 10.0 * PI)
   .fold(0.0, |sin_error, x| todo!());
Run Code Online (Sandbox Code Playgroud)