Solve linear Equation System
Asked Answered
T

2

7

I have two (mathematical) functions:

y = x
y = -2x + 3

This is solved by y = 1 and x = 1. See picture:

enter image description here

How can I make Julia do this for me?

Tko answered 3/5, 2020 at 7:45 Comment(0)
O
19

This is a set of linear equations so first rearrange them in the following way:

-x + y = 0
2x + y = 3

and you see that they are in the form of a linear equation system A*v=b where. A is a matrix:

julia> A = [-1 1; 2 1]
2×2 Array{Int64,2}:
 -1  1
  2  1

and b is a vector:

julia> b = [0, 3]
2-element Array{Int64,1}:
 0
 3

Now v contains your unknown variables x and y. You can now solve the system using the left division operator \:

julia> A\b
2-element Array{Float64,1}:
 1.0
 1.0

If you had a more general system of non-linear equations you should use NLsolve.jl package:

julia> using NLsolve

julia> function f!(F, v)
           x = v[1]
           y = v[2]
           F[1] = -x + y
           F[2] = 2*x + y - 3
       end
f! (generic function with 1 method)

julia> res = nlsolve(f!, [0.0; 0.0])
Results of Nonlinear Solver Algorithm
 * Algorithm: Trust-region with dogleg and autoscaling
 * Starting Point: [0.0, 0.0]
 * Zero: [1.0000000000003109, 0.9999999999999647]
 * Inf-norm of residuals: 0.000000
 * Iterations: 2
 * Convergence: true
   * |x - x'| < 0.0e+00: false
   * |f(x)| < 1.0e-08: true
 * Function Calls (f): 3
 * Jacobian Calls (df/dx): 3

julia> res.zero
2-element Array{Float64,1}:
 1.0000000000003109
 0.9999999999999647

(note that in f! we define two outputs F[1] and F[2] to be equal to zero - you have to rearrange your equations in this way).

For more details how to use NLsolve.jl see https://github.com/JuliaNLSolvers/NLsolve.jl.

Orlina answered 3/5, 2020 at 7:52 Comment(1)
So cool! Great recommendation!Zollverein
B
3

Mr @bogumił-kamiński gave an excellent answer. However, just a friendly reminder, the solution MAY NOT EXIST for some other system of linear equations. In that case, you'll get a SingularException. Consider checking if the solution exists or not. For example,

using LinearAlgebra;
"""

y = x         =>     x - y = 0  =>    |1  -1| X = |0|  => AX = B => X = A⁻¹B     
y = -2x + 3          2x + y = 3       |2   1|     |3|
"""

function solution()
  A::Matrix{Int64} = Matrix{Int64}([1 -1; 2 1]);
  
  br::Matrix{Int64} = Matrix{Int64}([0 3]);
  bc = transpose(br);

  # bc::Matrix{Int64} = Matrix{Int64}([0 ;3;;]);   # I missed a semicolon, that's why I got an error
  # println(bc);

  if(det(A) == 0)    # existence check
    println("soln doesnot exist. returning...");
    return
  end
  A⁻¹ = inv(A);
  println("solution exists:")
  X = A⁻¹ * bc;
  println(X);

end

solution();
Begin answered 21/7, 2022 at 14:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.