Skip to content

Commit 3a0201c

Browse files
fix: implement ln fallback locally
1 parent 9571ec9 commit 3a0201c

File tree

3 files changed

+30
-9
lines changed

3 files changed

+30
-9
lines changed

Cargo.lock

-7
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

-1
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ spki = { version = "0.8.0-rc.1", default-features = false, features = ["alloc"]
2424
zeroize = { version = "1.5", features = ["alloc"] }
2525
crypto-bigint = { version = "0.6.0", default-features = false, features = ["zeroize", "alloc"] }
2626
crypto-primes = { version = "0.6.0", default-features = false }
27-
libm = "0.2"
2827

2928
# optional dependencies
3029
sha1 = { version = "=0.11.0-pre.4", optional = true, default-features = false, features = ["oid"] }

src/algorithms/generate.rs

+30-1
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,20 @@ fn logf(val: f64) -> f64 {
126126
/// Natural logarithm for `f64`.
127127
#[cfg(not(feature = "std"))]
128128
fn logf(val: f64) -> f64 {
129-
libm::logf(val as f32) as f64
129+
logf_approx(val as f32) as f64
130+
}
131+
132+
/// Ln implementation based on
133+
/// <https://gist.github.com/LingDong-/7e4c4cae5cbbc44400a05fba65f06f23>
134+
#[cfg(any(not(feature = "std"), test))]
135+
fn logf_approx(x: f32) -> f32 {
136+
let bx: u32 = x.to_bits();
137+
let ex: u32 = bx >> 23;
138+
let t: i32 = (ex as i32) - 127;
139+
let bx = 1065353216 | (bx & 8388607);
140+
let x = f32::from_bits(bx);
141+
142+
-1.49278 + (2.11263 + (-0.729104 + 0.10969 * x) * x) * x + core::f32::consts::LN_2 * (t as f32)
130143
}
131144

132145
fn generate_prime_with_rng<R: CryptoRngCore>(rng: &mut R, bit_length: u32) -> BoxedUint {
@@ -141,6 +154,7 @@ fn generate_prime_with_rng<R: CryptoRngCore>(rng: &mut R, bit_length: u32) -> Bo
141154
#[cfg(test)]
142155
mod tests {
143156
use super::*;
157+
use rand::Rng;
144158
use rand_chacha::{rand_core::SeedableRng, ChaCha8Rng};
145159

146160
const EXP: u64 = 65537;
@@ -186,4 +200,19 @@ mod tests {
186200
key_generation!(key_generation_multi_8_576, 8, 576);
187201
// TODO: reenable, currently slow
188202
// key_generation!(key_generation_multi_16_1024, 16, 1024);
203+
204+
#[test]
205+
fn test_log_approx() {
206+
let mut rng = ChaCha8Rng::from_seed([42; 32]);
207+
208+
for i in 0..100 {
209+
println!("round {i}");
210+
let prime_limit: f64 = rng.gen();
211+
let a = logf(prime_limit);
212+
let b = logf_approx(prime_limit as f32);
213+
214+
let diff = a - b as f64;
215+
assert!(diff < 0.001, "{} != {}", a, b);
216+
}
217+
}
189218
}

0 commit comments

Comments
 (0)