Go语言常用的向量计算函数
以下都已float64类型为例
1. zeros()和ones()
package main import ( "fmt" "math/rand" ) func printSlise(array []float64) { for i := 0; i < len(array); i++ { fmt.Print(array[i], " ") } fmt.Println() } func zeros(dim int) []float64 { var vector []float64 for i := 0; i < dim; i++ { vector = append(vector, float64(0)) } return vector } func ones(dim int) []float64 { var vector []float64 for i := 0; i < dim; i++ { vector = append(vector, float64(1)) } return vector } func main() { printSlise(zeros(5)) printSlise(ones(6)) fmt.Println("---end---") }
结果:
0 0 0 0 0
1 1 1 1 1 1
---end---
向量的运算有常数和向量逐元素相加减乘,向量和向量逐元素相加减乘,向量和向量内积
2. 常数和向量运算:
package main import ( "fmt" "math/rand" ) func printSlise(array []float64) { for i := 0; i < len(array); i++ { fmt.Print(array[i], " ") } fmt.Println() } // 向量逐元素加某常数 func scalaAdd(v []float64, a float64) []float64 { var res []float64 for i := range v { res = append(res, a+v[i]) } return res } // 向量逐元素减某常数 func scalaSubtract(v []float64, a float64) []float64 { var res []float64 for i := range v { res = append(res, v[i]-a) } return res } // 向量逐元素乘某常数 func scalaMulti(v []float64, a float64) []float64 { var res []float64 for i := range v { res = append(res, a*v[i]) } return res } func main() { var arr = []float64{4, 5, 7, 8, 2, 1} var arr1 = scalaAdd(arr, 10) arr2 := scalaSubtract(arr, 2) arr3 := scalaMulti(arr, 10) printSlise(arr) printSlise(arr1) printSlise(arr2) printSlise(arr3) fmt.Println("---end---") }
结果如下:
4 5 7 8 2 1
14 15 17 18 12 11
2 3 5 6 0 -1
40 50 70 80 20 10
3. 向量和向量逐元素运算:
结果:
4 5 7 8 2 1
14 15 17 18 12 11
18 20 24 26 14 12
10 10 10 10 10 10
56 75 119 144 24 11
4. 向量内积:
package main import ( "fmt" "math/rand" ) func printSlise(array []float64) { for i := 0; i < len(array); i++ { fmt.Print(array[i], " ") } fmt.Println() } // 向量内积 func innerMulti(v1 []float64, v2 []float64) float64 { var res float64 for i := range v1 { res += v1[i] * v2[i] } return res } func main() { var arr0 = []float64{1, 2, 3, 4, 5} var arr1 = scalaAdd(arr0, 0) var arr2 = innerMulti(arr0, arr1) fmt.Println(arr2) fmt.Println("---end---") }
结果:
55