Swift: How to solve a system of linear equations? - COFPROG

Swift: How to solve a system of linear equations?

Question: How to solve a system of linear equations?

Answer:


// You can use the Cramer's rule to solve a system of linear equations.

// Here is an example of solving the following system of equations:

// 2x + 3y = 8

// x - y = 1


func solveLinearEquations(a: Double, b: Double, c: Double, d: Double, e: Double, f: Double) -> (Double, Double) {

    let x = (e*d - b*f) / (a*d - b*c)

    let y = (a*f - e*c) / (a*d - b*c)

    return (x, y)

}


let (x, y) = solveLinearEquations(a: 2, b: 3, c: 1, d: -1, e: 8, f: 1)

print("x = \(x), y = \(y)") // x = 2.0, y = 2.0


Previous
Next Post »

BOOK OF THE DAY