1+ // ______ ______ _____ _ _ //
2+ // | ____| ____| /\ / ____| (_) | | //
3+ // | |__ | |__ / \ | (___ ___ ____ _ ____ | |_ //
4+ // | __| | __| / /\ \ \___ \ / __| __| | _ \| __| //
5+ // | | | |____ / ____ \ ____) | (__| | | | |_) | | //
6+ // |_| |______/_/ \_\_____/ \___|_| |_| __/| | //
7+ // | | | | //
8+ // |_| | |_ //
9+ // Website: https://feascript.com/ \__| //
10+
11+ /**
12+ * Solves a system of linear equations using the Jacobi iterative method
13+ * @param {Array<Array<number>> } A - The coefficient matrix (must be square)
14+ * @param {Array<number> } b - The right-hand side vector
15+ * @param {Array<number> } x0 - Initial guess for solution vector
16+ * @param {number } [maxIterations=100] - Maximum number of iterations
17+ * @param {number } [tolerance=1e-7] - Convergence tolerance
18+ * @returns {object } An object containing:
19+ * - solution: The solution vector
20+ * - iterations: The number of iterations performed
21+ * - converged: Boolean indicating whether the method converged
22+ */
23+ export function jacobiMethod ( A , b , x0 , maxIterations = 100 , tolerance = 1e-7 ) {
24+ const n = A . length ; // Size of the square matrix
25+ let x = [ ...x0 ] ; // Current solution (starts with initial guess)
26+ let xNew = new Array ( n ) ; // Next iteration's solution
27+
28+ for ( let iteration = 0 ; iteration < maxIterations ; iteration ++ ) {
29+ // Perform one iteration
30+ for ( let i = 0 ; i < n ; i ++ ) {
31+ let sum = 0 ;
32+ // Calculate sum of A[i][j] * x[j] for j ≠ i
33+ for ( let j = 0 ; j < n ; j ++ ) {
34+ if ( j !== i ) {
35+ sum += A [ i ] [ j ] * x [ j ] ;
36+ }
37+ }
38+ // Update xNew[i] using the Jacobi formula
39+ xNew [ i ] = ( b [ i ] - sum ) / A [ i ] [ i ] ;
40+ }
41+
42+ // Check convergence
43+ let maxDiff = 0 ;
44+ for ( let i = 0 ; i < n ; i ++ ) {
45+ maxDiff = Math . max ( maxDiff , Math . abs ( xNew [ i ] - x [ i ] ) ) ;
46+ }
47+
48+ // Update x for next iteration
49+ x = [ ...xNew ] ;
50+
51+ // If difference is small enough, we've converged
52+ if ( maxDiff < tolerance ) {
53+ return {
54+ solution : x ,
55+ iterations : iteration + 1 ,
56+ converged : true
57+ } ;
58+ }
59+ }
60+
61+ // If we reach here, we didn't converge within maxIterations
62+ return {
63+ solution : x ,
64+ iterations : maxIterations ,
65+ converged : false
66+ } ;
67+ }
0 commit comments