solving linear equation with triangular matrix


/ Published in: Python
Save to your folder(s)

it's a assessement from a lecture about numerics...have to code it in C...but just for trying out my algo, was python just fine.


Copy this code and paste it in your HTML
  1. A=[3,-5,1,0,0,0.5,2,-9,0,0,-1,3,0,0,0,9]
  2. b=[5,22,-8,-18]
  3. x=b
  4. n=4
  5.  
  6. # think of the dictionary as two dimensional array
  7. # i = \[0..n-1\], j=\[i..n-1\]
  8. # A\[i,j\] (2.dim) \hat{=} A\[i*4+j\] (1.dim)
  9. # to save memory, we calculate it directly in x
  10. # we could save more memory by leaving out x or b :)
  11. # the inner loop is running through: n < (n(n+1)/2)+1 < n^2
  12. for i in range(n-1,-1,-1):
  13. for j in range(n-1,i,-1):
  14. x[i] -= A[i*n+j]*x[j]
  15. x[i] /= A[i*n+i]
  16.  
  17. print x

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.