Skip to content

Commit

Permalink
Merge pull request #2487 from o1-labs/dw/mvpoly-implement-neg
Browse files Browse the repository at this point in the history
MVPoly: implement Neg
  • Loading branch information
dannywillems authored Aug 27, 2024
2 parents 2bff712 + 2e6b59f commit ac8b7b9
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 1 deletion.
27 changes: 26 additions & 1 deletion mvpoly/src/prime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@
use std::{
collections::HashMap,
fmt::{Debug, Formatter, Result},
ops::{Add, Mul, Sub},
ops::{Add, Mul, Neg, Sub},
};

use ark_ff::{One, PrimeField, Zero};
Expand Down Expand Up @@ -395,6 +395,31 @@ impl<F: PrimeField, const N: usize, const D: usize> Sub<&Dense<F, N, D>> for &De
}
}

// Negation
impl<F: PrimeField, const N: usize, const D: usize> Neg for Dense<F, N, D> {
type Output = Self;

fn neg(self) -> Self::Output {
let mut result = Dense::new();
for i in 0..self.coeff.len() {
result.coeff[i] = -self.coeff[i];
}
result
}
}

impl<F: PrimeField, const N: usize, const D: usize> Neg for &Dense<F, N, D> {
type Output = Dense<F, N, D>;

fn neg(self) -> Self::Output {
let mut result = Dense::new();
for i in 0..self.coeff.len() {
result.coeff[i] = -self.coeff[i];
}
result
}
}

// Multiplication
impl<F: PrimeField, const N: usize, const D: usize> Mul<Dense<F, N, D>> for Dense<F, N, D> {
type Output = Self;
Expand Down
35 changes: 35 additions & 0 deletions mvpoly/tests/prime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,3 +202,38 @@ fn test_sub_zero() {
let p2 = p1.clone() - zero.clone();
assert_eq!(p1.clone(), p2);
}

#[test]
fn test_neg() {
let mut rng = o1_utils::tests::make_test_rng(None);
let p1 = Dense::<Fp, 3, 4>::random(&mut rng);
let p2 = -p1.clone();

// Test that p1 + (-p1) = 0
let sum = p1.clone() + p2.clone();
assert_eq!(sum, Dense::<Fp, 3, 4>::zero());

// Test that -(-p1) = p1
let p3 = -p2;
assert_eq!(p1, p3);

// Test negation of zero
let zero = Dense::<Fp, 3, 4>::zero();
let neg_zero = -zero.clone();
assert_eq!(zero, neg_zero);
}

#[test]
fn test_neg_ref() {
let mut rng = o1_utils::tests::make_test_rng(None);
let p1 = Dense::<Fp, 3, 4>::random(&mut rng);
let p2 = -&p1;

// Test that p1 + (-&p1) = 0
let sum = p1.clone() + p2.clone();
assert_eq!(sum, Dense::<Fp, 3, 4>::zero());

// Test that -(-&p1) = p1
let p3 = -&p2;
assert_eq!(p1, p3);
}

0 comments on commit ac8b7b9

Please sign in to comment.