add sub ops for flat polynomial

This commit is contained in:
2026-04-22 00:43:03 +02:00
parent 6a8312dfe4
commit 04f5444c68
2 changed files with 27 additions and 29 deletions

View File

@@ -1,34 +1,17 @@
use circuit_polynomial::poly::flat; use circuit_polynomial::poly::flat;
use circuit_polynomial::poly::flat::Mono; use circuit_polynomial::var;
use circuit_polynomial::{var,poly::var::StaticVar};
fn main() { fn main() {
let poly: flat::Poly<StaticVar> = [ let poly = (2
( * ((var!("x", 1, 5) ^ 5) * (var!("x", 1, 2) ^ 5) * (var!("x", 2, 5) ^ 1)))
2, + (3 * ((var!("x", 1, 9) ^ 5) * (var!("x", 1, 2) ^ 5) * (var!("x", 2, 5) ^ 1)));
[
(var!("x", 1, 5), 5),
(var!("x", 1, 2), 5),
(var!("x", 2, 5), 1),
],
),
(
3,
[
(var!("x", 1, 9), 5),
(var!("x", 1, 2), 5),
(var!("x", 2, 5), 1),
],
),
]
.into();
let x=var!("x"); let x = var!("x");
let y=var!("y"); let y = var!("y");
let mono = 3*((&x^2)*(&y^4)); let other = -3 * ((&x ^ 2) * (&y ^ 4));
println!("{poly}"); println!("{poly}");
let z=poly+mono; let z = poly - other;
println!("{z}"); println!("{z}");
} }

View File

@@ -1,7 +1,7 @@
use itertools::Itertools; use itertools::Itertools;
use std::fmt::{self, Display}; use std::fmt::{self, Display};
use std::ops::{Add, BitXor, Mul}; use std::ops::{Add, Sub, BitXor, Mul};
use super::var::{StaticVar, Var}; use super::var::{StaticVar, Var};
use std::collections::HashMap; use std::collections::HashMap;
@@ -75,9 +75,11 @@ impl<V: Var, U: Into<V>> FromIterator<(U, u32)> for Mono<V> {
term.sort(); term.sort();
// Check duplicate variables // Check duplicate variables
assert!((term[..]) assert!(
(term[..])
.windows(2) .windows(2)
.all(|window| window[0].0 != window[1].0)); .all(|window| window[0].0 != window[1].0)
);
Mono { term } Mono { term }
} }
@@ -179,3 +181,16 @@ impl<V: Var> Add for Poly<V> {
self self
} }
} }
impl<V: Var> Sub for Poly<V> {
type Output = Poly<V>;
fn sub(mut self, other: Poly<V>) -> Self::Output {
for (mono, coeff) in other.mono {
let entry = self.mono.entry(mono).or_insert(0);
*entry -= coeff;
}
self.mono.retain(|_, &mut coeff| coeff != 0);
self
}
}