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