gpt4 book ai didi

Rust 'for loop'(从 c++ 转换而来)

转载 作者:行者123 更新时间:2023-12-03 11:25:45 29 4
gpt4 key购买 nike

尝试将此 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));
}

最佳答案

迭代整数

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

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!();
}

只需将 todo!() 替换为计算下一个 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!());

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

使用 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;
}

使用 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!();
}

更实用的方式

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!());

关于Rust 'for loop'(从 c++ 转换而来),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61327408/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com