官术网_书友最值得收藏!

Vector operations

As mentioned here, working with vectors necessitates the use of certain vector-/matrix-specific operations and rules. For example, how do we multiply vectors together? How do we know if two vectors are similar? Both gonum.org/v1/gonum/floats and gonum.org/v1/gonum/mat provide built-in methods and functions for vector/slice operations, such as dot products, sorting, and distance. We won't cover all of the functionality here, as there is quite a bit, but we can get a general feel for how we might work with vectors. First, we can work with gonum.org/v1/gonum/floats in the following way:

// Initialize a couple of "vectors" represented as slices.
vectorA := []float64{11.0, 5.2, -1.3}
vectorB := []float64{-7.2, 4.2, 5.1}

// Compute the dot product of A and B
// (https://en.wikipedia.org/wiki/Dot_product).
dotProduct := floats.Dot(vectorA, vectorB)
fmt.Printf("The dot product of A and B is: %0.2f\n", dotProduct)

// Scale each element of A by 1.5.
floats.Scale(1.5, vectorA)
fmt.Printf("Scaling A by 1.5 gives: %v\n", vectorA)

// Compute the norm/length of B.
normB := floats.Norm(vectorB, 2)
fmt.Printf("The norm/length of B is: %0.2f\n", normB)

We can also do similar operations with gonum.org/v1/gonum/mat:

// Initialize a couple of "vectors" represented as slices.
vectorA := mat.NewVector(3, []float64{11.0, 5.2, -1.3})
vectorB := mat.NewVector(3, []float64{-7.2, 4.2, 5.1})

// Compute the dot product of A and B
// (https://en.wikipedia.org/wiki/Dot_product).
dotProduct := mat.Dot(vectorA, vectorB)
fmt.Printf("The dot product of A and B is: %0.2f\n", dotProduct)

// Scale each element of A by 1.5.
vectorA.ScaleVec(1.5, vectorA)
fmt.Printf("Scaling A by 1.5 gives: %v\n", vectorA)

// Compute the norm/length of B.
normB := blas64.Nrm2(3, vectorB.RawVector())
fmt.Printf("The norm/length of B is: %0.2f\n", normB)

The semantics are similar in the two cases. If you are only working with vectors (not matrices), and/or you just need some lightweight and quick operations on slices of floats, then gonum.org/v1/gonum/floats is likely a good choice. However, if you are working with both matrices and vectors, and/or want access to a wider range of vector/matrix functionality, you are likely better off with gonum.org/v1/gonum/mat (along with occasional references to gonum.org/v1/gonum/blas/blas64).

主站蜘蛛池模板: 仪征市| 铜鼓县| 红桥区| 河南省| 七台河市| 襄汾县| 白河县| 东源县| 兴安县| 新闻| 阳朔县| 泗洪县| 西乌| 合山市| 耿马| 抚州市| 拉萨市| 金山区| 全州县| 子洲县| 抚宁县| 定襄县| 海丰县| 尼勒克县| 理塘县| 永靖县| 西乌珠穆沁旗| 奈曼旗| 鹤山市| 嘉义市| 朝阳县| 扎兰屯市| 马鞍山市| 祁门县| 淮北市| 南雄市| 尉氏县| 新野县| 惠安县| 盐边县| 神农架林区|