Go语言常用的向量计算函数

以下都已float64类型为例

 

1. zeros()和ones()

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. 常数和向量运算:

func scalaAdd(v []float64, a float64) []float64 {
    var res []float64
    var n int = len(v)
    for i := 0; i < n; i++ {
        res = append(res, a+v[i])
    }
    return res
}

func scalaSubtract(v []float64, a float64) []float64 {
    var res []float64
    var n int = len(v)
    for i := 0; i < n; i++ {
        res = append(res, v[i]-a)
    }
    return res
}

func scalaMulti(v []float64, a float64) []float64 {
    var res []float64
    var n int = len(v)
    for i := 0; i < n; i++ {
        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. 向量和向量逐元素运算:

func add(v1 []float64, v2 []float64) []float64 {
    var res []float64
    var n int = len(v2)
    for i := 0; i < n; i++ {
        res = append(res, v1[i]+v2[i])
    }
    return res
}

func subtract(v1 []float64, v2 []float64) []float64 {
    var res []float64
    var n int = len(v2)
    for i := 0; i < n; i++ {
        res = append(res, v1[i]-v2[i])
    }
    // fmt.Println(res)
    return res
}

func multiply(v1 []float64, v2 []float64) []float64 {
    var res []float64
    var n int = len(v2)
    for i := 0; i < n; i++ {
        res = append(res, v1[i]*v2[i])
    }
    return res
}
func main() {
    var arr0 = []float64{4, 5, 7, 8, 2, 1}
    var arr1 = scalaAdd(arr0, 10)
    var arr2 = add(arr1, arr0)
    var arr3 = subtract(arr1, arr0)
    arr4 := multiply(arr1, arr0)
    printSlise(arr0)
    printSlise(arr1)
    fmt.Println()
    printSlise(arr2)
    printSlise(arr3)
    printSlise(arr4)
    fmt.Println("---end---")
}

结果:

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. 向量内积:

func innerMulti(v1 []float64, v2 []float64) float64 {
    var res float64
    var n int = len(v1)
    for i := 0; i < n; i++ {
        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

上一篇:request和requestScope等拿取参数的区别;


下一篇:LeetCode 485 . 最大连续1的个数