我有一个ndarray 2维数组,我想乘以行具有相同的号码,说这里。
当我使用2维数组时,它可以正常工作,f64
但我希望它对所有浮点数通用。这就是为什么我使用Float
num-traits。但是,它不再编译。
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
在这样的操作使用,则必须要求ndarray::ScalarOperand
的T
。这是固定的代码:
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;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句