Swift 实现向量及矩阵基本运算

比如向量点乘、矩阵的逆、高斯消元法等
Github: https://github.com/zhouyijian/LinearAlgebra
向量示例代码

//
//  Vector.swift
//  Vector
//
//  Created by 周一见 on 2020/7/31.
//  Copyright © 2020 周一见. All rights reserved.
//

import Foundation
struct Vector {
    
    let values: [Double]
    
    init(array: [Double]) {
        self.values = array
    }
    
    init(zeroDim: Int) {
        self.init(array: Array.init(repeating: 0, count: zeroDim))
    }
    
    func getLen() -> Int {
        return values.count
    }
    
    func getItem(index: Int) -> Double {
        return values[index]
    }
    
}

precedencegroup DotProductPrecedence {
    lowerThan: AdditionPrecedence
    associativity: left
}

infix operator •: DotProductPrecedence

//MARK: - 规范化
extension Vector {
    func norm() -> Double {
        var sum = 0.0
        for i in self.values {
            sum += (i * i)
        }
        return sum.squareRoot()
    }
    
    func normalize() -> Vector {
        if self.norm() < epsilon {
            fatalError("Can not normalize zero vector")
        } else {
            return self / self.norm()
        }
    }
}

// MARK: - Operators
extension Vector {
    static func + (left: Vector, right: Vector) -> Vector {
        assert(left.getLen() == right.getLen())
        var sum = Array.init(repeating: 0.0, count: left.getLen())
        for i in 0.. Vector {
        assert(left.getLen() == right.getLen())
        var sum = Array.init(repeating: 0.0, count: left.getLen())
        for i in 0.. Vector {
        var sum = Array.init(repeating: 0.0, count: vector.getLen())
        for i in 0.. Vector {
        var sum = Array.init(repeating: 0.0, count: right.getLen())
        for i in 0.. Vector {
        return right * left
    }
    
    static func / (left: Vector, right: Double) -> Vector {
        return left * (1 / right)
    }
    
    static func • (left: Vector, right: Vector) -> Double {
        assert(left.getLen() == right.getLen())
        var sum = 0.0
        for i in 0.. Bool {
        assert(left.getLen() == right.getLen())
        for i in 0..

你可能感兴趣的:(Swift 实现向量及矩阵基本运算)