Merge pull request #521 from mir-protocol/fix_inv_mod_xn

Fix inv mod xn
This commit is contained in:
wborgeaud 2022-03-21 06:13:06 +01:00 committed by GitHub
commit 2cedd1b02a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 12 additions and 3 deletions

View File

@ -86,8 +86,14 @@ impl<F: Field> PolynomialCoeffs<F> {
/// Computes the inverse of `self` modulo `x^n`.
pub fn inv_mod_xn(&self, n: usize) -> Self {
assert!(n > 0, "`n` needs to be nonzero");
assert!(self.coeffs[0].is_nonzero(), "Inverse doesn't exist.");
// If polynomial is constant, return the inverse of the constant.
if self.degree_plus_one() == 1 {
return Self::new(vec![self.coeffs[0].inverse()]);
}
let h = if self.len() < n {
self.padded(n)
} else {

View File

@ -526,12 +526,15 @@ mod tests {
fn test_inv_mod_xn() {
type F = GoldilocksField;
let mut rng = thread_rng();
let a_deg = rng.gen_range(1..1_000);
let a_deg = rng.gen_range(0..1_000);
let n = rng.gen_range(1..1_000);
let a = PolynomialCoeffs::new(F::rand_vec(a_deg));
let mut a = PolynomialCoeffs::new(F::rand_vec(a_deg + 1));
if a.coeffs[0].is_zero() {
a.coeffs[0] = F::ONE; // First coefficient needs to be nonzero.
}
let b = a.inv_mod_xn(n);
let mut m = &a * &b;
m.coeffs.drain(n..);
m.coeffs.truncate(n);
m.trim();
assert_eq!(
m,