1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#![no_std]
pub const INV_LOG2_E_Q1DOT31: u64 = 0x58b90bfc;
pub const INV_LOG2_10_Q1DOT31: u64 = 0x268826a1;
pub fn log2fix(x: u32, precision: u8) -> i32 {
let mut x = x;
let mut b: i32 = 1 << (precision - 1);
let mut y: i32 = 0;
if precision < 1 || precision > 31 {
return i32::MAX;
}
if x == 0 {
return i32::MIN;
}
while x < (1 << precision) {
x = x << 1;
y -= 1 << precision;
}
while x >= (2 << precision) {
x = x >> 1;
y += 1 << precision;
}
let mut z = x as u64;
for _ in 0..precision {
z = (z * z) >> precision;
if z >= (2 << precision) {
z = z >> 1;
y += b;
}
b = b >> 1;
}
y
}
pub fn logefix(x: u32, precision: u8) -> i32 {
let t = (log2fix(x, precision) as u64).overflowing_mul(INV_LOG2_E_Q1DOT31).0;
(t >> 31) as i32
}
pub fn log10fix(x: u32, precision: u8) -> i32 {
let t = (log2fix(x, precision) as u64).overflowing_mul(INV_LOG2_10_Q1DOT31).0;
(t >> 31) as i32
}
#[cfg(test)]
mod tests {
}