Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update CHANGELOG: Fix handling of duplicate terms in SparsePolynomial #915

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

### Bugfixes

- (`ark-poly`) Fix handling of duplicate terms in `SparsePolynomial::from_coefficients_vec`. Terms with the same degree are now correctly merged, and zero coefficient terms are removed.

## v0.5.0

- [\#772](https://github.com/arkworks-rs/algebra/pull/772) (`ark-ff`) Implementation of `mul` method for `BigInteger`.
Expand Down
31 changes: 19 additions & 12 deletions poly/src/polynomial/univariate/sparse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -236,20 +236,27 @@ impl<F: Field> SparsePolynomial<F> {
}

/// Constructs a new polynomial from a list of coefficients.
/// The function does not combine like terms and so multiple monomials
/// of the same degree are ignored.
pub fn from_coefficients_vec(mut coeffs: Vec<(usize, F)>) -> Self {
// While there are zeros at the end of the coefficient vector, pop them off.
while coeffs.last().map_or(false, |(_, c)| c.is_zero()) {
coeffs.pop();
}
// Ensure that coeffs are in ascending order.
// Sort terms by degree
coeffs.sort_by(|(c1, _), (c2, _)| c1.cmp(c2));
// Check that either the coefficients vec is empty or that the last coeff is
// non-zero.
assert!(coeffs.last().map_or(true, |(_, c)| !c.is_zero()));

Self { coeffs }

// Merge duplicate terms
let mut merged_coeffs: Vec<(usize, F)> = Vec::new();
for (degree, coeff) in coeffs {
if let Some((last_degree, last_coeff)) = merged_coeffs.last_mut() {
if *last_degree == degree {
*last_coeff += coeff; // Combine coefficients for duplicate degrees
continue;
}
}
merged_coeffs.push((degree, coeff));
}

// Remove zero coefficient terms
merged_coeffs.retain(|(_, coeff)| !coeff.is_zero());

// Create the SparsePolynomial
Self { coeffs: merged_coeffs }
}

/// Perform a naive n^2 multiplication of `self` by `other`.
Expand Down
Loading