Skip to content

Non-linear Equations

This module includes root-finding algorithms and numerical solvers for non-linear equations.

Gauss_elimination_pivoted(matrix, vector)

Function for Gaussian elimination using partial pivoting to reduce numerical errors.

Swaps rows to ensure the largest absolute value in the current column becomes the pivot element, minimizing floating-point inaccuracies.

Parameters:

Name Type Description Default
matrix ndarray

Coefficient matrix.

required
vector ndarray

Right-hand side vector.

required

Returns:

Name Type Description
x ndarray

Solution vector.

Source code in openum/NonLinEq.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
def Gauss_elimination_pivoted(matrix: np.ndarray, vector: np.ndarray) -> np.ndarray:
    """
    Function for Gaussian elimination using partial pivoting to reduce numerical errors.

    Swaps rows to ensure the largest absolute value in the current column 
    becomes the pivot element, minimizing floating-point inaccuracies.

    Args:
        matrix (numpy.ndarray): Coefficient matrix.
        vector (numpy.ndarray): Right-hand side vector.

    Returns:
        x (numpy.ndarray): Solution vector.
    """
    U_Matrix = np.copy(matrix).astype(float)
    U_vector = np.copy(vector).astype(float)
    rows, columns = U_Matrix.shape
    x = np.zeros(rows)

    # Forward elimination with partial pivoting
    for i in range(rows - 1):
        # --- NEW: Partial Pivoting ---
        # Find the row with the largest absolute value in the current column i
        max_row_index = i + np.argmax(np.abs(U_Matrix[i:rows, i]))

        if max_row_index != i:
            # Swap the current row i with the row containing the maximum value
            U_Matrix[[i, max_row_index]] = U_Matrix[[max_row_index, i]]
            U_vector[[i, max_row_index]] = U_vector[[max_row_index, i]]
        # -----------------------------

        if np.isclose(U_Matrix[i, i], 0):
            raise ValueError("Matrix is singular or nearly singular.")

        for j in range(i + 1, rows):
            factor = U_Matrix[j, i] / U_Matrix[i, i]
            U_Matrix[j] -= factor * U_Matrix[i]
            U_vector[j] -= factor * U_vector[i]

    # Back substitution (same as before)
    for i in range(rows - 1, -1, -1):
        if np.isclose(U_Matrix[i, i], 0):
            raise ValueError("Matrix is singular or nearly singular.")
        x[i] = (U_vector[i] - np.dot(U_Matrix[i, i + 1:], x[i + 1:])) / U_Matrix[i, i]

    return x

bisection_method(x1, x2, f, max_iter, eps=1e-06)

Solving nonlinear equations with bisection method.

Parameters:

Name Type Description Default
x1 float

Lower bound of the interval.

required
x2 float

Upper bound of the interval.

required
f function

Function for which the root is to be found.

required
max_iter int

Maximum number of iterations.

required
eps float

Convergence criterion.

1e-06

Returns:

Name Type Description
float float

Approximation of the root, or None if no convergence.

Source code in openum/NonLinEq.py
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def bisection_method(x1: float, x2: float, f: Callable, max_iter: int, eps: float=1e-6) -> float:
    """
    Solving nonlinear equations with bisection method.

    Args:
        x1 (float): Lower bound of the interval.
        x2 (float): Upper bound of the interval.
        f (function): Function for which the root is to be found.
        max_iter (int): Maximum number of iterations.
        eps (float): Convergence criterion.

    Returns:
        float: Approximation of the root, or None if no convergence.
    """
    x_new = (x1+x2)/2
    for _ in range(max_iter):

        if f(x_new)*f(x1) < 0:
            x2 = x_new

        elif f(x_new)*f(x2) < 0:
            x1 = x_new

        x_new = (x1+x2)/2

        if np.abs(f(x_new)) < eps:
            return x_new

    print("Did not converge.")
    return None

jacobi_method(A, b, init_val, max_iter, tol=1e-06)

Solve a linear system using the iterative Jacobi method.

In contrast to Gauss-Seidel, the Jacobi method uses only the values from the previous iteration step to calculate the new approximations.

Parameters:

Name Type Description Default
A ndarray

Coefficient matrix.

required
b ndarray

Right-hand side vector.

required
init_val list

Initial guess for the solution vector x.

required
max_iter int

Maximum number of iterations.

required
tol float

Convergence tolerance.

1e-06

Returns:

Type Description
ndarray

numpy.ndarray: Solution vector if convergence is achieved.

Source code in openum/NonLinEq.py
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
def jacobi_method(A: np.ndarray, b: np.ndarray, init_val: list, max_iter: int, tol: float=1e-6) -> np.ndarray:
    """
    Solve a linear system using the iterative Jacobi method.

    In contrast to Gauss-Seidel, the Jacobi method uses only the values 
    from the previous iteration step to calculate the new approximations.

    Args:
        A (numpy.ndarray): Coefficient matrix.
        b (numpy.ndarray): Right-hand side vector.
        init_val (list): Initial guess for the solution vector x.
        max_iter (int): Maximum number of iterations.
        tol (float): Convergence tolerance.

    Returns:
        numpy.ndarray: Solution vector if convergence is achieved.
    """
    rows, cols = A.shape
    if rows != cols:
        raise ValueError("Coefficient matrix A must be square.")

    x_old = np.array(init_val, dtype=float)
    x_new = np.zeros_like(x_old)

    for iteration in range(max_iter):
        for i in range(rows):
            if A[i, i] == 0:
                raise ValueError("Diagonal element is zero, cannot proceed with Jacobi method.")

            # Sum over all j != i
            s = 0.0
            for j in range(cols):
                if j != i:
                    s += A[i, j] * x_old[j]

            x_new[i] = (b[i] - s) / A[i, i]

        # Check for convergence (using infinity norm)
        if np.linalg.norm(x_new - x_old, ord=np.inf) < tol:
            return x_new

        # Update x_old for the next iteration
        x_old = x_new.copy()

    raise RuntimeError("Jacobi method did not converge within the maximum number of iterations.")

linear_interpolation(f, x0, x1, max_iter, epsilon=1e-06)

Find the root of a function using linear interpolation.

Parameters:

Name Type Description Default
f function

Function for which the root is to be found.

required
x0 float

Initial guess.

required
x1 float

Second guess.

required
max_iter int

Maximum number of iterations.

required
epsilon float

Convergence criterion.

1e-06

Returns:

Name Type Description
x2 float

Approximation of the root, or None if no convergence.

Source code in openum/NonLinEq.py
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
def linear_interpolation(f: Callable, x0: float, x1: float, max_iter: int, epsilon: float=1e-6) -> float:
    """
    Find the root of a function using linear interpolation.

    Args:
        f (function): Function for which the root is to be found.
        x0 (float): Initial guess.
        x1 (float): Second guess.
        max_iter (int): Maximum number of iterations.
        epsilon (float): Convergence criterion.

    Returns:
        x2 (float): Approximation of the root, or None if no convergence.
    """
    for _ in range(max_iter):
        f0, f1 = f(x0), f(x1)

        if f1 == f0:  # Prevent division by zero
            print("Division by zero encountered.")
            return None

        x2 = x1 - f1 * (x1 - x0) / (f1 - f0)

        if np.abs(x2 - x1) < epsilon:
            print(f"Root found: {f(x2)}")
            return x2

        x0, x1 = x1, x2

    print("Did not converge.")
    return None

newton_halley(f, df, d2f, x0, max_iter, epsilon=1e-06)

Find the root of a function using Newton-Halley method.

Parameters:

Name Type Description Default
f function

Function for which the root is to be found.

required
df function

First derivative of the function.

required
d2f function

Second derivative of the function.

required
x0 float

Initial guess.

required
max_iter int

Maximum number of iterations.

required
epsilon float

Convergence criterion.

1e-06

Returns:

Name Type Description
x float

Approximation of the root, or None if no convergence.

Source code in openum/NonLinEq.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
def newton_halley(f: Callable, df: Callable, d2f: Callable, x0: float, max_iter: int, epsilon: float=1e-6) -> float:
    """
    Find the root of a function using Newton-Halley method.

    Args:
        f (function): Function for which the root is to be found.
        df (function): First derivative of the function.
        d2f (function): Second derivative of the function.
        x0 (float): Initial guess.
        max_iter (int): Maximum number of iterations.
        epsilon (float): Convergence criterion.

    Returns:
        x (float): Approximation of the root, or None if no convergence.
    """
    x = x0
    for _ in range(max_iter):
        fx = f(x)
        dfx = df(x)
        d2fx = d2f(x)

        if np.abs(fx) < epsilon:
            return x

        if dfx == 0:
            print("Derivative is zero. Cannot proceed.")
            return None

        x -= (2*fx*dfx)/(2*dfx**2-d2fx*fx)

    print("Did not converge.")
    return None

newtons_method(f, df, x0, max_iter, epsilon=1e-06)

Find the root of a function using Newton's method.

Parameters:

Name Type Description Default
f function

Function for which the root is to be found.

required
df function

Derivative of the function.

required
x0 float

Initial guess.

required
max_iter int

Maximum number of iterations.

required
epsilon float

Convergence criterion.

1e-06

Returns:

Name Type Description
x float

Approximation of the root, or None if no convergence.

Source code in openum/NonLinEq.py
 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
def newtons_method(f: Callable, df: Callable, x0: float, max_iter: int, epsilon: float=1e-6) -> float:
    """
    Find the root of a function using Newton's method.

    Args:
        f (function): Function for which the root is to be found.
        df (function): Derivative of the function.
        x0 (float): Initial guess.
        max_iter (int): Maximum number of iterations.
        epsilon (float): Convergence criterion.

    Returns:
        x (float): Approximation of the root, or None if no convergence.
    """
    x = x0
    for _ in range(max_iter):
        fx = f(x)
        dfx = df(x)

        if np.abs(fx) < epsilon:
            return x

        if dfx == 0:
            print("Derivative is zero. Cannot proceed.")
            return None

        x -= fx / dfx

    print("Did not converge.")
    return None

solve_fixed_point(f1, f2, x_init, y_init, max_iter, tol=1e-08)

Solve a system of equations using fixed-point iteration.

Parameters:

Name Type Description Default
f1 function

Function for the first equation.

required
f2 function

Function for the second equation.

required
x_init float

Initial guess for x.

required
y_init float

Initial guess for y.

required
max_iter int

Maximum number of iterations.

required
tol float

Convergence criterion.

1e-08

Returns:

Name Type Description
tuple tuple[float, float]

Approximations of the roots (x, y), or (None, None) if no convergence.

Source code in openum/NonLinEq.py
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
def solve_fixed_point(f1: Callable, f2: Callable, x_init: float, y_init: float, max_iter: int, tol=1e-8) -> tuple[float,float]:
    """
    Solve a system of equations using fixed-point iteration.

    Args:
        f1 (function): Function for the first equation.
        f2 (function): Function for the second equation.
        x_init (float): Initial guess for x.
        y_init (float): Initial guess for y.
        max_iter (int): Maximum number of iterations.
        tol (float): Convergence criterion.

    Returns:
        tuple: Approximations of the roots (x, y), or (None, None) if no convergence.
    """
    x, y = x_init, y_init

    for i in range(max_iter):
        x_new = f1(y)
        y_new = f2(x)

        if np.abs(x_new - x) < tol and np.abs(y_new - y) < tol:
            print(f"Converged in {i + 1} iterations.")
            return x_new, y_new

        x, y = x_new, y_new

    print("Did not converge.")
    return None, None