Skip to main content

Fp

Struct Fp 

Source
pub struct Fp(/* private fields */);
Expand description

An element of F_p, always stored reduced in [0, p).

Implementations§

Source§

impl Fp

Source

pub const ZERO: Fp

Source

pub const ONE: Fp

Source

pub fn new(v: u64) -> Self

Examples found in repository?
examples/bench.rs (line 33)
15fn main() {
16    println!("{:<26} {:>10} {:>10} {:>10}", "transform", "n", "1 thread", "auto");
17    for log in [16, 20, 22] {
18        let n = 1usize << log;
19        let mut x: Vec<Fp> = (0..n as u64).map(Fp::new).collect();
20        let (p1, pa) = (Ntt::new(n).with_threads(1), Ntt::new(n));
21        let a = time(|| p1.forward(&mut x));
22        let b = time(|| pa.forward(&mut x));
23        println!("{:<26} {:>10} {:>10.2} {:>10.2}", "Ntt", n, a, b);
24    }
25    for n in [65535usize, 255 * 4096, 65537 * 15] {
26        let x: Vec<Fp> = (0..n as u64).map(Fp::new).collect();
27        let (p1, pa) = (Dft::new(n).with_threads(1), Dft::new(n));
28        let a = time(|| { p1.forward(&x); });
29        let b = time(|| { pa.forward(&x); });
30        println!("{:<26} {:>10} {:>10.2} {:>10.2}", format!("Dft {:?}", pa.factors()), n, a, b);
31    }
32    for n in [100_000usize, 1_000_000] {
33        let q = Fp::new(3);
34        let x: Vec<Fp> = (0..n as u64).map(Fp::new).collect();
35        let c = ChirpZ::new(n, n, q);
36        println!("{:<26} {:>10} {:>10} {:>10.2}", "ChirpZ (q=3)", n, "-", time(|| { c.apply(&x); }));
37        let ic = InverseChirpZ::new(n, q);
38        println!("{:<26} {:>10} {:>10} {:>10.2}", "InverseChirpZ (q=3)", n, "-", time(|| { ic.apply(&x); }));
39    }
40}
More examples
Hide additional examples
examples/paper_demo.rs (line 43)
12fn main() {
13    println!("== Paper parameters (binary case) ==");
14    println!("{:>5} {:>3} {:>4} {:>6} {:>6} {:>4} {:>8} {:>12}", "m", "r", "B", "u", "v", "D", "D<m?", "exc.frac");
15    for m in [3, 8, 16, 32, 48, 64, 65, 80, 96, 128, 256, 1024] {
16        let p = Params::paper(m);
17        println!(
18            "{:>5} {:>3} {:>4} {:>6} {:>6} {:>4} {:>8} {:>12.3e}",
19            m,
20            paper_r(m),
21            paper_half_width(m),
22            p.u,
23            p.v,
24            p.degree(),
25            p.window_bites(),
26            p.exception_fraction()
27        );
28    }
29    let t = paper_threshold_m();
30    let d = Params::paper(t).degree();
31    let axes = 2 * (t + d - 1);
32    println!(
33        "\nWindow first bites at m = {t} (D = {d}). One kernel level then uses about A = 2(m+D-1) = {axes} axes,"
34    );
35    println!("so a single level needs N >= 2^{axes} (rough lower estimate, not a figure from the paper).");
36
37    println!("\n== Exact repair check ==");
38    for (m, b) in [(6usize, 1.0f64), (8, 1.5), (10, 2.0)] {
39        let params = Params::with_half_width(m, b);
40        let w = 1usize << m;
41        let shifts = balanced_shifts(m, w);
42        let xs: Vec<Vec<Fp>> = (0..w)
43            .map(|i| (0..1u64 << m).map(|k| Fp::new((i as u64 + 1) * 1_000_003 + k * k)).collect())
44            .collect();
45
46        // Prediction alone (no repair) is wrong at the exceptions.
47        let ctr0 = OpCounter::default();
48        let wrong_rows = (0..w)
49            .filter(|&i| apply_predictor(&params, shifts[i], &xs[i], &ctr0) != apply_f_reference(m, &xs[i]))
50            .count();
51
52        let ctr = OpCounter::default();
53        let out = apply_f_repaired(&params, &xs, &shifts, None, &ctr);
54        let exact = xs.iter().zip(&out.rows).all(|(x, y)| *y == apply_f_reference(m, x));
55        println!(
56            "m={m:>2} window=[{},{}] D={} W={w}: prediction-only wrong rows {wrong_rows}/{w}, \
57             s={} (paper budget W/2m^3 = {}), repaired exact = {exact}, \
58             Q-calls={} (naive {}), spectral rows={}",
59            params.u,
60            params.v,
61            params.degree(),
62            out.s,
63            paper_exception_budget(w, m),
64            ctr.q(),
65            w * m,
66            ctr.spectral()
67        );
68        assert!(exact);
69    }
70    println!("\nNote: Q-calls are high because the predictor is expanded directly");
71    println!("(no matrix-root/routing). This checks correctness, not the paper's cost savings.");
72
73    println!("\n== Cyclic / abelian-group DFT via Newton + in-place Toeplitz (grids.tex) ==");
74    use log_fft::paper::grid::{naive_group_dft, newton::vandermonde, AxisPlan, GroupDft};
75    let cases: Vec<(usize, Option<u64>)> = vec![(17, None), (255, None), (1020, None), (4096, None), (1000, Some(3)), (777, Some(5))];
76    for (a, q) in cases {
77        let (plan, label) = match q {
78            None => (AxisPlan::dft(a), "DFT".to_string()),
79            Some(q) => (AxisPlan::geometric(a, Fp::new(q)), format!("V_a(q={q})")),
80        };
81        let x: Vec<Fp> = (0..a as u64).map(|i| Fp::new(i * 2654435761 + 1)).collect();
82        let mut scratch = vec![Fp::ZERO; a];
83        let y = plan.forward(&x, &mut scratch);
84        let v = vandermonde(a, plan.q);
85        let expect: Vec<Fp> = (0..a).map(|j| (0..a).fold(Fp::ZERO, |s, k| s + v[j][k] * x[k])).collect();
86        let ok = y == expect;
87        let back = plan.inverse(&y, &mut scratch) == x;
88        let restored = scratch.iter().all(|v| *v == Fp::ZERO);
89        println!(
90            "{label:>11} a={a:>5}  b={:>5} factors={:<14}  forward exact={ok}  inverse exact={back}  scratch restored={restored}",
91            plan.engine.dft.b,
92            format!("{:?}", plan.engine.dft.factors),
93        );
94        assert!(ok && back && restored);
95    }
96    let dims = [3usize, 5, 17, 4];
97    let g = GroupDft::new(&dims);
98    let x: Vec<Fp> = (0..g.len() as u64).map(|i| Fp::new(i * i + 9)).collect();
99    let exact = g.forward(&x) == naive_group_dft(&dims, &x);
100    println!("G = Z3 x Z5 x Z17 x Z4 (N={}): exact = {exact}", g.len());
101    assert!(exact);
102}
Source

pub fn from_i64(v: i64) -> Self

Source

pub fn value(self) -> u64

The canonical representative in [0, p).

Source

pub fn from_canonical(v: u64) -> Option<Self>

Some(x) if v < p, otherwise None (no silent reduction).

Source

pub fn as_u64_slice(xs: &[Fp]) -> &[u64]

View field elements as their canonical u64 values (zero-copy).

Source

pub fn from_canonical_slice(xs: &[u64]) -> Option<&[Fp]>

View u64s as field elements without copying, if every value is < p.

Source

pub fn from_canonical_slice_mut(xs: &mut [u64]) -> Option<&mut [Fp]>

Mutable zero-copy view of u64s as field elements, if every value is < p.

Source

pub fn pow(self, e: u64) -> Self

Source

pub fn inv(self) -> Self

Multiplicative inverse. Panics on zero.

Source

pub fn sign(e: i64) -> Self

(-1)^e for any integer e.

Source

pub fn root_of_unity(n: u64) -> Self

A primitive n-th root of unity. n must divide p - 1.

Trait Implementations§

Source§

impl Add for Fp

Source§

type Output = Fp

The resulting type after applying the + operator.
Source§

fn add(self, rhs: Fp) -> Fp

Performs the + operation. Read more
Source§

impl AddAssign for Fp

Source§

fn add_assign(&mut self, rhs: Fp)

Performs the += operation. Read more
Source§

impl Clone for Fp

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Copy for Fp

Source§

impl Debug for Fp

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Fp

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl Display for Fp

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Div for Fp

Source§

fn div(self, rhs: Fp) -> Fp

Panics on division by zero.

Source§

type Output = Fp

The resulting type after applying the / operator.
Source§

impl DivAssign for Fp

Source§

fn div_assign(&mut self, rhs: Fp)

Performs the /= operation. Read more
Source§

impl Eq for Fp

Source§

impl From<Fp> for u64

Source§

fn from(v: Fp) -> u64

Converts to this type from the input type.
Source§

impl From<bool> for Fp

Source§

fn from(v: bool) -> Self

Converts to this type from the input type.
Source§

impl From<i64> for Fp

Source§

fn from(v: i64) -> Self

Converts to this type from the input type.
Source§

impl From<u32> for Fp

Source§

fn from(v: u32) -> Self

Converts to this type from the input type.
Source§

impl From<u64> for Fp

Source§

fn from(v: u64) -> Self

Reduces modulo p.

Source§

impl Hash for Fp

Source§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Mul for Fp

Source§

type Output = Fp

The resulting type after applying the * operator.
Source§

fn mul(self, rhs: Fp) -> Fp

Performs the * operation. Read more
Source§

impl MulAssign for Fp

Source§

fn mul_assign(&mut self, rhs: Fp)

Performs the *= operation. Read more
Source§

impl Neg for Fp

Source§

type Output = Fp

The resulting type after applying the - operator.
Source§

fn neg(self) -> Fp

Performs the unary - operation. Read more
Source§

impl Ord for Fp

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for Fp

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl PartialOrd for Fp

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

fn lt(&self, other: &Rhs) -> bool

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

fn le(&self, other: &Rhs) -> bool

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

fn gt(&self, other: &Rhs) -> bool

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

fn ge(&self, other: &Rhs) -> bool

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Product for Fp

Source§

fn product<I: Iterator<Item = Fp>>(iter: I) -> Fp

Takes an iterator and generates Self from the elements by multiplying the items.
Source§

impl<'a> Product<&'a Fp> for Fp

Source§

fn product<I: Iterator<Item = &'a Fp>>(iter: I) -> Fp

Takes an iterator and generates Self from the elements by multiplying the items.
Source§

impl StructuralPartialEq for Fp

Source§

impl Sub for Fp

Source§

type Output = Fp

The resulting type after applying the - operator.
Source§

fn sub(self, rhs: Fp) -> Fp

Performs the - operation. Read more
Source§

impl SubAssign for Fp

Source§

fn sub_assign(&mut self, rhs: Fp)

Performs the -= operation. Read more
Source§

impl Sum for Fp

Source§

fn sum<I: Iterator<Item = Fp>>(iter: I) -> Fp

Takes an iterator and generates Self from the elements by “summing up” the items.
Source§

impl<'a> Sum<&'a Fp> for Fp

Source§

fn sum<I: Iterator<Item = &'a Fp>>(iter: I) -> Fp

Takes an iterator and generates Self from the elements by “summing up” the items.

Auto Trait Implementations§

§

impl Forget for Fp

§

impl Freeze for Fp

§

impl Move for Fp

§

impl RefUnwindSafe for Fp

§

impl Send for Fp

§

impl Sync for Fp

§

impl Unpin for Fp

§

impl UnsafeUnpin for Fp

§

impl UnwindSafe for Fp

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.