4 // http://en.wikibooks.org/wiki/Fortran/Fortran_examples
6 function gauss_sparse(num_iter, tol, b, A, x, actual_iter)
8 ! This function solves a system of equations (Ax = b) by using the Gauss-Seidel Method
14 ! Input: its value cannot be modified from within the function
15 integer, intent(in) :: num_iter
16 real, intent(in) :: tol
17 real, intent(in), dimension(1:) :: b
18 real, intent(in), dimension(1:,1:) :: A
20 ! Input/Output: its input value is used within the function, and can be modified
21 real, intent(inout), dimension(1:) :: x
23 ! Output: its value is modified from within the function, only if the argument is required
24 integer, optional, intent(out) :: actual_iter
31 n = ubound(b, dim = 1) ! Size of array, obtained using ubound intrinsic function
35 ! Compute solution until convergence
36 convergence_loop: do while (tol_max >= tol .and. iter < num_iter); iter = iter + 1
38 tol_max = -1. ! Reset the tolerance value
40 ! Compute solution for the k-th iteration
41 iteration_loop: do i = 1, n
43 ! Compute the current x-value
44 xk = (b(i) - dot_product(A(i,1:i-1),x(1:i-1)) - dot_product(A(i,i+1:n),x(i+1:n))) / A(i, i)
46 ! Compute the error of the solution
47 ! dot_product(a,v)=a'b
48 tol_max = max((abs(x(i) - xk)/(1. + abs(xk))) ** 2, abs(A(i, i) * (x(i) - xk)), tol_max)
51 end do convergence_loop
53 if (present(actual_iter)) actual_iter = iter
54 gauss_sparse = tol_max
56 end function gauss_sparse
62 var dot_product = { |a, b| (a * b).sum };
63 var gauss_sparse = { | num_iter, tol, b, a, x |
71 // Compute solution until convergence
72 while { (tol_max >= tol) and: (iter < num_iter) }
76 tol_max = -1.0; // Reset the tolerance value
77 // Compute solution for the k-th iteration
80 // Compute the current x-value
81 xk = (b[i] - dot_product(a[i][i-1], x[i-1]) - dot_product(a[i][i+1], x[i+1])) / a[i][i];
82 // Compute the error of the solution
83 // dot_product(a,v)=a'b
84 tol_max = max((abs(x[i] - xk)/(1.0 + abs(xk))) ** 2, abs(a[i][i] * (x[i] - xk)), tol_max);
91 gauss_sparse.(8, 2, [0, 1, 2, 3, 4], [[0, 1, 2], [1, 2, 3]], [0, 1, 2, 3, 4]);