poulpy/math/tests/rescaling_rns.rs
math/tests/rescaling_rns.rsRaw
1use math::poly::PolyRNS;
2use math::ring::RingRNS;
3use num_bigint::BigInt;
4use num_bigint::Sign;
5use sampling::source::Source;
6
7#[test]
8fn rescaling_rns_u64() {
9 let n = 1 << 10;
10 let moduli: Vec<u64> = vec![0x1fffffffffc80001u64, 0x1fffffffffe00001u64];
11 let ring_rns: RingRNS<u64> = RingRNS::new(n, moduli);
12
13 test_div_floor_by_last_modulus::<false>(&ring_rns);
14 test_div_floor_by_last_modulus::<true>(&ring_rns);
15}
16
17fn test_div_floor_by_last_modulus<const NTT: bool>(ring_rns: &RingRNS<u64>) {
18 let seed: [u8; 32] = [0; 32];
19 let mut source: Source = Source::new(seed);
20
21 let mut a: PolyRNS<u64> = ring_rns.new_polyrns();
22 let mut b: PolyRNS<u64> = ring_rns.new_polyrns();
23 let mut c: PolyRNS<u64> = ring_rns.at_level(ring_rns.level() - 1).new_polyrns();
24
25 // Allocates a random PolyRNS
26 ring_rns.fill_uniform(&mut source, &mut a);
27
28 // Maps PolyRNS to [BigInt]
29 let mut coeffs_a: Vec<BigInt> = (0..a.n()).map(|i| BigInt::from(i)).collect();
30 ring_rns
31 .at_level(a.level())
32 .to_bigint_inplace(&a, 1, &mut coeffs_a);
33
34 // Performs c = intt(ntt(a) / q_level)
35 if NTT {
36 ring_rns.ntt_inplace::<false>(&mut a);
37 }
38
39 ring_rns.div_floor_by_last_modulus::<NTT>(&a, &mut b, &mut c);
40
41 if NTT {
42 ring_rns.at_level(c.level()).intt_inplace::<false>(&mut c);
43 }
44
45 // Exports c to coeffs_c
46 let mut coeffs_c = vec![BigInt::from(0); c.n()];
47 ring_rns
48 .at_level(c.level())
49 .to_bigint_inplace(&c, 1, &mut coeffs_c);
50
51 // Performs floor division on a
52 let scalar_big = BigInt::from(ring_rns.0[ring_rns.level()].modulus.q);
53 coeffs_a.iter_mut().for_each(|a| {
54 // Emulates floor division in [0, q-1] and maps to [-(q-1)/2, (q-1)/2-1]
55 *a /= &scalar_big;
56 if a.sign() == Sign::Minus {
57 *a -= 1;
58 }
59 });
60
61 assert!(coeffs_a == coeffs_c);
62}