gpt4 book ai didi

rust - 将大 float 转换为整数索引时的向量索引 "out of bounds"

转载 作者:行者123 更新时间:2023-11-29 08:10:13 29 4
gpt4 key购买 nike

我一直在尝试使用以下函数在 m 和 n 之间生成素数:

//the variable sieve is a list of primes between 1 and 32000
//The primes up to 100 are definitely correct
fn sieve_primes(sieve: &Vec<usize>, m: &usize, n: &usize) -> Vec<usize> {
let size: usize = *n - *m + 1;
let mut list: Vec<usize> = Vec::with_capacity(size);

for i in *m..(*n + 1) {
list.push(i);
}
for i in sieve {
for j in ( ((*m as f32) / (*i as f32)).ceil() as usize)..( (((*n as f32) / (*i as f32)).floor() + 1.0) as usize) {
println!("{} ",j);
if j != 1 {list[i * j - *m] = 0;}
}
}

let mut primes: Vec<usize> = Vec::new();
for num in &list{
if *num >= 2 {primes.push(*num);}
}
primes
}

这适用于较小(小于 1000000 左右)的 m 和 n 值,但是对于数十亿/亿左右的数字,它在运行时会失败。

m = 99999999,n = 100000000 的输出是:

33333334
thread '' panicked at 'index out of bounds: the len is 2 but the index is 3'

如果您查看这些数字,这没有任何意义。首先,它似乎跳过了素数列表中的数字 2。其次,当 i = 3 时,for 语句应简化为 for j in 33333333..333333334,出于某种原因,它从 33333334 开始 j。

最佳答案

f32 只能精确表示所有的24位整数,对应的大概是1600万(实际是16777216)。上面有空隙,最多只能表示 33554432 个偶数。因此,在您的示例中,33333333 不能表示为 f32,而是四舍五入为 33333334。

您不需要使用 float 来舍入整数除法的结果。直接使用整数既更快又没有精度问题。对于非负整数,您可以执行以下操作:

fn main() {
let a = 12;
let b = 7;
println!("rounded down: {}", a / b);
println!("rounded: {}", (a + b / 2) / b);
println!("rounded up: {}", (a + b - 1) / b);
}

关于rust - 将大 float 转换为整数索引时的向量索引 "out of bounds",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35076068/

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