我正在用Rust编写神经网络的实现,尝试计算两个矩阵的点积。我有以下代码:
fn dot_product(a: Vec<f64>, b: Vec<f64>) -> f64 {
// Calculate the dot product of two vectors.
assert_eq!(a.len(), b.len());
let mut product: f64 = 0.0;
for i in 0..a.len() {
product += a[i] * b[i];
}
product
}
这个操作需要两个向量
a
和 b
(长度相同),并逐元素进行乘法运算(将向量 a
中的值1与向量 b
中的值1相乘,然后将结果加到向量 a
中的值2和向量 b
中的值2上,以此类推...)。如果有更高效的方法,请说明是什么以及如何实现?
a.into_iter().zip(b).map(|(a, b)| a*b).sum()
。但我认为这种方法的速度与其他方法相比是相当快的,而不是显著更快或更慢。 - trent