1#[allow(dead_code)]
3const E: f32 = 2.7182818284590452353602874713527;
5const N: f32 = 0.1428571428571428571428571428571; pub fn log(n: f32, r: f32) -> f32 {
9 if n > r - 1.0 {1.0 + log(n / r, r)}
10 else {0.0}
11}
12
13pub fn log2n(n: f32) -> f32 {
15 if n > 1.0 {1.0 + log2n(n / 2.0)}
16 else {0.0}
17}
18
19pub fn exp(mut x: f32) -> f32 {
21 x = 1.0 + x / 1024.0;
22 x *= x; x *= x; x *= x; x *= x;
23 x *= x; x *= x; x *= x; x *= x;
24 x *= x; x *= x;
25 return x;
26}
27
28fn newton_sqrt(x: f32, n: f32) -> f32 {
29 if (x == f32::INFINITY) || (x == -f32::INFINITY) || (n == f32::INFINITY) || (n == -f32::INFINITY) {
30 return f32::NAN;
31 }
32
33 let mut res: f32 = x * 0.14285714285714285714285714285714;
34
35 loop {
36 let pre_res: f32 = res;
37 let a: f32 = res.powf(n);
38
39 res = res - ((a - x) / (n * (a / res)));
40
41 if pre_res == res { break }
42 }
43
44 return res
45}
46
47pub fn bakhshali_sqrt(x: f32) -> f32 {
48 let mut res: f32;
49 let mut a: f32;
50 let mut b: f32;
51
52 if (x == 0.0) || (x == 1.0) {
53 return x;
54 }
55
56 else if x < 0.0 {
57 return f32::NAN;
58 }
59
60 res = x * 0.25;
61
62 loop {
63 let pre_res: f32 = res;
64
65 a = (x - (res * res)) / (2.0 * res);
66 b = res + a;
67 res = b - ((a * a) / (2.0 * b));
68
69 if pre_res == res {
70 break;
71 }
72 }
73
74 res
75}
76
77pub fn babylonian_sqrt(x: f32) -> f32 {
78 if (x == 0.0) || (x == 1.0) {
79 return x
80 }
81 else if x < 0.0 {
82 return f32::MAX
83 }
84
85 let mut res: f32 = x * 0.25;
86
87 loop {
88 let pre_res: f32 = res;
89 res = 0.5 * (res + (x / res));
90
91 if pre_res == res { break }
92 }
93 res
94 }
95
96#[cfg(test)]
97mod test {
98 use super::*;
99
100 #[test]
101 fn test() {
102 let newton1: f32 = newton_sqrt(9.0, 2.0); assert_eq!(newton1, 3.0);
104
105 let newton2: f32 = newton_sqrt(8.0, 3.0); assert_eq!(newton2, 2.0);
107
108 let bakhshali1: f32 = bakhshali_sqrt(9.0); assert_eq!(bakhshali1, 3.0);
110
111 let bakhshali2: f32 = bakhshali_sqrt(0.0); assert_eq!(bakhshali2, 0.0);
113
114 let babylonian1: f32 = babylonian_sqrt(9.0); assert_eq!(babylonian1, 3.0);
116
117 let babylonian2: f32 = babylonian_sqrt(0.0); assert_eq!(babylonian2, 0.0);
119 }
120}