Skip to content

Commit 1bf1413

Browse files
Fixes #14817
1 parent e3b01ec commit 1bf1413

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

linear_algebra/src/polynom_for_points.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,12 @@ def points_to_polynomial(coordinates: list[list[int]]) -> str:
3333
Traceback (most recent call last):
3434
...
3535
ValueError: The program cannot work out a fitting polynomial.
36+
>>> points_to_polynomial([[0, 1], [1, 2], [2, 5]])
37+
'f(x)=x^2*1.0+x^1*0.0+x^0*1.0'
38+
>>> points_to_polynomial([[1, 2], [0, 1], [2, 5]])
39+
Traceback (most recent call last):
40+
...
41+
ValueError: The program cannot work out a fitting polynomial.
3642
"""
3743
if len(coordinates) == 0 or not all(len(pair) == 2 for pair in coordinates):
3844
raise ValueError("The program cannot work out a fitting polynomial.")
@@ -65,6 +71,41 @@ def points_to_polynomial(coordinates: list[list[int]]) -> str:
6571
for number in range(x):
6672
if count == number:
6773
continue
74+
if matrix[count][count] == 0:
75+
# Diagonal element is zero which results in zero-division-error
76+
# as per bug #14817.
77+
# Using partial pivoting: before each elimination step, swap in a row
78+
# whose matrix[r][count] is non-zero (largest magnitude).
79+
# This removes the zero-pivot crash and improves numerical stability.
80+
81+
swap_row_index = count
82+
max_col_value = matrix[count][count]
83+
# Search downwards from current row as earlier rows are
84+
# already processed.
85+
for row in range(count, x):
86+
if matrix[row][count] > max_col_value:
87+
swap_row_index = row
88+
max_col_value = matrix[row][count]
89+
90+
# If maximum value found in the current column is
91+
# again zero, raise error.
92+
if int(max_col_value) == 0:
93+
raise ValueError(
94+
"The program cannot work out a fitting polynomial."
95+
)
96+
97+
# Swap pivot row with row index found in previous step,
98+
# with maximum value present in matrix[r][count] column.
99+
matrix[count], matrix[swap_row_index] = (
100+
matrix[swap_row_index],
101+
matrix[count],
102+
)
103+
vector[count], vector[swap_row_index] = (
104+
vector[swap_row_index],
105+
vector[count],
106+
)
107+
# Continue to perform scaling row reduction.
108+
68109
fraction = matrix[number][count] / matrix[count][count]
69110
for counting_columns, item in enumerate(matrix[count]):
70111
# manipulating all the values in the matrix
@@ -101,3 +142,7 @@ def points_to_polynomial(coordinates: list[list[int]]) -> str:
101142
print(points_to_polynomial([[1, 3], [2, 6], [3, 11]]))
102143
print(points_to_polynomial([[1, -3], [2, -6], [3, -11]]))
103144
print(points_to_polynomial([[1, 5], [2, 2], [3, 9]]))
145+
146+
# Added under bug fix: #14817
147+
print(points_to_polynomial([[0, 1], [1, 2], [2, 5]]))
148+
print(points_to_polynomial([[1, 2], [0, 1], [2, 5]]))

0 commit comments

Comments
 (0)