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