Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions linear_algebra/src/polynom_for_points.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,12 @@ def points_to_polynomial(coordinates: list[list[int]]) -> str:
Traceback (most recent call last):
...
ValueError: The program cannot work out a fitting polynomial.
>>> points_to_polynomial([[0, 1], [1, 2], [2, 5]])
'f(x)=x^2*1.0+x^1*0.0+x^0*1.0'
>>> points_to_polynomial([[1, 2], [0, 1], [2, 5]])
Traceback (most recent call last):
...
ValueError: The program cannot work out a fitting polynomial.
"""
if len(coordinates) == 0 or not all(len(pair) == 2 for pair in coordinates):
raise ValueError("The program cannot work out a fitting polynomial.")
Expand Down Expand Up @@ -65,6 +71,41 @@ def points_to_polynomial(coordinates: list[list[int]]) -> str:
for number in range(x):
if count == number:
continue
if matrix[count][count] == 0:
# Diagonal element is zero which results in zero-division-error
# as per bug #14817.
# Using partial pivoting: before each elimination step, swap in a row
# whose matrix[r][count] is non-zero (largest magnitude).
# This removes the zero-pivot crash and improves numerical stability.

swap_row_index = count
max_col_value = matrix[count][count]
# Search downwards from current row as earlier rows are
# already processed.
for row in range(count, x):
if matrix[row][count] > max_col_value:
swap_row_index = row
max_col_value = matrix[row][count]

# If maximum value found in the current column is
# again zero, raise error.
if int(max_col_value) == 0:
raise ValueError(
"The program cannot work out a fitting polynomial."
)

# Swap pivot row with row index found in previous step,
# with maximum value present in matrix[r][count] column.
matrix[count], matrix[swap_row_index] = (
matrix[swap_row_index],
matrix[count],
)
vector[count], vector[swap_row_index] = (
vector[swap_row_index],
vector[count],
)
# Continue to perform scaling row reduction.

fraction = matrix[number][count] / matrix[count][count]
for counting_columns, item in enumerate(matrix[count]):
# manipulating all the values in the matrix
Expand Down Expand Up @@ -101,3 +142,7 @@ def points_to_polynomial(coordinates: list[list[int]]) -> str:
print(points_to_polynomial([[1, 3], [2, 6], [3, 11]]))
print(points_to_polynomial([[1, -3], [2, -6], [3, -11]]))
print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))

# Added under bug fix: #14817
print(points_to_polynomial([[0, 1], [1, 2], [2, 5]]))
print(points_to_polynomial([[1, 2], [0, 1], [2, 5]]))