【问题标题】:How to write a function to do the dot product on n-dimensional vector?如何编写一个函数来对 n 维向量进行点积?
【发布时间】:2015-02-03 19:20:05
【问题描述】:

首先,这里简要介绍一下dot product 是什么。

我希望能够拥有一段代码,我可以通过以下方式使用它:

 let x = Vector<Double>(dimensions: 3)
 let y = Vector<Double>(dimensions: 3)

 //...
 //assign some values (coordinates) to x and y
 //x.dotProduct(y)

如何将dotProduct 实现为 方法?

以下是不起作用的:

func dot(vector: Point<T>) -> Double {
    var sum: Double = 0.0
    for index in 0...vector.size {
       sum += sum + vector[index] * point[index]
    }
}

错误信息是:

error: cannot invoke '*' with an argument list of type '(@lvalue T, $T14)'

func dot

 func dot(vector: Point<T>) -> T {
    var sum = 0 as T
    println(point.count)

    for index in 0..<point.count{
        println(vector[index])
        println(point[index])

        sum += vector[index] * point[index]
    }

    return sum
}

【问题讨论】:

标签: swift operator-overloading


【解决方案1】:

更新 4:

这行得通:

class Vector<T: SummableMultipliable> {
    var dimensions: Int
    var coordinates: [T]

    init(dimensions: Int) {
        self.dimensions = dimensions
        self.coordinates = [T](count: dimensions, repeatedValue: 0 as T)
    }

    func dotProduct<T>(vector: Vector<T>) -> T {
        assert(self.dimensions == vector.dimensions, "Vectors don't have the same dimensions.")

        //as @AirspeedVelocity suggested:
        return reduce(Zip2(self.coordinates, vector.coordinates), 0) { sum, pair in sum + pair.0 * pair.1 }

        //the old version:
        /*var sum: T = 0

        for dimension in 0..<self.dimensions {
            sum = sum + (self.coordinates[dimension] as T * vector.coordinates[dimension])
        }

        return sum*/
    }
}

protocol SummableMultipliable: Equatable, IntegerLiteralConvertible {
    func +(lhs: Self, rhs: Self) -> Self
    func *(lhs: Self, rhs: Self) -> Self
}

extension Int: SummableMultipliable { }
extension Double: SummableMultipliable { }

var x = Vector<Int>(dimensions: 3)
var y = Vector<Int>(dimensions: 3)

x.coordinates[0] = 3
x.coordinates[1] = 2
x.coordinates[2] = 1

y.coordinates[0] = 3
y.coordinates[1] = 2
y.coordinates[2] = 1

println(x.dotProduct(y)) //prints 14

【讨论】:

  • 忘记点积,我什至无法让你的不出现段错误
  • 嗯 - 我目前遇到了问题:'T' is not identical to 'UInt8' sum += left.coordinates[dimension] as T * right.coordinates[dimension] as T,但我正在努力解决。
  • 我让它停止崩溃,但行: sum += left.coordinates[dimension] as T * right.coordinates[dimension] as T 给出“错误:'T' 与'不同UInt8'"
  • @user678392 你知道如何解决这个问题吗?
  • 是的,为什么会这样?为什么需要 Vector 的扩展?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-19
  • 2022-12-11
相关资源
最近更新 更多