gpt4 book ai didi

generics - 如何将 ndarray 中的元素与 Rust 中的泛型相乘?

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

我有一个 ndarray 二维数组,我试图用相同的数字乘以一行,如 here 所述.

当我使用 f64 的二维数组时它工作正常,但我希望它对所有类型的 float 都是通用的。这就是我使用 num-traits 中的 Float 的原因。但是,它不再编译。

use ndarray::{Array2, Axis};

fn gauss(pivot: [usize; 2], table: &mut Array2<f64>) {
for i in 0..table.len_of(Axis(0)) {
if i != pivot[0] {
let pivot_n = table[pivot];
let make_zero = table[[i, pivot[1]]];
let mut row_pivot = table.row(pivot[0]).to_owned();
let mut row_make_zero = table.row_mut(i);
row_make_zero *= pivot_n;
row_pivot *= -make_zero;
row_make_zero += &row_pivot;
}
}
}

use num::Float;
use std::ops::MulAssign;

fn gauss_2<T: Float + MulAssign>(pivot: [usize; 2], table: &mut Array2<T>) {
for i in 0..table.len_of(Axis(0)) {
if i != pivot[0] {
let pivot_n = table[pivot];
let make_zero = table[[i, pivot[1]]];
let mut row_pivot = table.row(pivot[0]).to_owned();
let mut row_make_zero = table.row_mut(i);
row_make_zero *= pivot_n;
row_pivot *= -make_zero;
row_make_zero += &row_pivot;
}
}
}

它显示的错误是:

error[E0308]: mismatched types
--> src/lib.rs:27:30
|
27 | row_make_zero *= pivot_n;
| ^^^^^^^ expected reference, found type parameter
|
= note: expected type `&ndarray::ArrayBase<_, _>`
found type `T`

error[E0308]: mismatched types
--> src/lib.rs:28:26
|
28 | row_pivot *= -make_zero;
| ^^^^^^^^^^ expected reference, found type parameter
|
= note: expected type `&ndarray::ArrayBase<_, _>`
found type `T`

error[E0368]: binary assignment operation `+=` cannot be applied to type `ndarray::ArrayBase<ndarray::ViewRepr<&mut T>, ndarray::dimension::dim::Dim<[usize; 1]>>`
--> src/lib.rs:29:13
|
29 | row_make_zero += &row_pivot;
| -------------^^^^^^^^^^^^^^
| |
| cannot use `+=` on type `ndarray::ArrayBase<ndarray::ViewRepr<&mut T>, ndarray::dimension::dim::Dim<[usize; 1]>>`
|
= note: an implementation of `std::ops::AddAssign` might be missing for `ndarray::ArrayBase<ndarray::ViewRepr<&mut T>, ndarray::dimension::dim::Dim<[usize; 1]>>`

最佳答案

如果你想在那种操作中使用T,你必须为T要求ndarray::ScalarOperand。这是固定的代码:

use ndarray::{Array2, ScalarOperand};
use num::Float;
use std::ops::{AddAssign, MulAssign};

fn gauss<T>(pivot: [usize; 2], table: &mut Array2<T>)
where
T: Float + MulAssign + AddAssign + ScalarOperand,
{
for i in 0..table.len_of(Axis(0)) {
if i != pivot[0] {
// Aplicar GAUSS a la fila
let pivot_n = table[pivot];
let make_zero = table[[i, pivot[1]]];
// Multiplicar la fila de make_zero por pivot_n
let mut row_pivot = table.row(pivot[0]).to_owned();
let mut row_make_zero = table.row_mut(i);
row_make_zero *= pivot_n;
row_pivot *= -make_zero;
row_make_zero += &row_pivot;
}
}
}

关于generics - 如何将 ndarray 中的元素与 Rust 中的泛型相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55882605/

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