From 1bf14131eebb5f7d3bbec5714b461aa9ea76b636 Mon Sep 17 00:00:00 2001 From: AshwiniKP-STech Date: Fri, 19 Jun 2026 18:59:44 +0530 Subject: [PATCH] Fixes #14817 --- linear_algebra/src/polynom_for_points.py | 45 ++++++++++++++++++++++++ 1 file changed, 45 insertions(+) diff --git a/linear_algebra/src/polynom_for_points.py b/linear_algebra/src/polynom_for_points.py index 452f3edd4aee..e4b9722b5969 100644 --- a/linear_algebra/src/polynom_for_points.py +++ b/linear_algebra/src/polynom_for_points.py @@ -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.") @@ -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 @@ -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]]))