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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
#[allow(dead_code)]
const E: f32 = 2.7182818284590452353602874713527;
const N: f32 = 0.1428571428571428571428571428571; pub fn log(n: f32, r: f32) -> f32 {
if n > r - 1.0 {1.0 + log(n / r, r)}
else {0.0}
}
pub fn log2n(n: f32) -> f32 {
if n > 1.0 {1.0 + log2n(n / 2.0)}
else {0.0}
}
pub fn exp(mut x: f32) -> f32 {
x = 1.0 + x / 1024.0;
x *= x; x *= x; x *= x; x *= x;
x *= x; x *= x; x *= x; x *= x;
x *= x; x *= x;
return x;
}
fn newton_sqrt(x: f32, n: f32) -> f32 {
if (x == f32::INFINITY) || (x == -f32::INFINITY) || (n == f32::INFINITY) || (n == -f32::INFINITY) {
return f32::NAN;
}
let mut res: f32 = x * 0.14285714285714285714285714285714;
loop {
let pre_res: f32 = res;
let a: f32 = res.powf(n);
res = res - ((a - x) / (n * (a / res)));
if pre_res == res { break }
}
return res
}
pub fn bakhshali_sqrt(x: f32) -> f32 {
let mut res: f32;
let mut a: f32;
let mut b: f32;
if (x == 0.0) || (x == 1.0) {
return x;
}
else if x < 0.0 {
return f32::NAN;
}
res = x * 0.25;
loop {
let pre_res: f32 = res;
a = (x - (res * res)) / (2.0 * res);
b = res + a;
res = b - ((a * a) / (2.0 * b));
if pre_res == res {
break;
}
}
res
}
pub fn babylonian_sqrt(x: f32) -> f32 {
if (x == 0.0) || (x == 1.0) {
return x
}
else if x < 0.0 {
return f32::MAX
}
let mut res: f32 = x * 0.25;
loop {
let pre_res: f32 = res;
res = 0.5 * (res + (x / res));
if pre_res == res { break }
}
res
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test() {
let newton1: f32 = newton_sqrt(9.0, 2.0); assert_eq!(newton1, 3.0);
let newton2: f32 = newton_sqrt(8.0, 3.0); assert_eq!(newton2, 2.0);
let bakhshali1: f32 = bakhshali_sqrt(9.0); assert_eq!(bakhshali1, 3.0);
let bakhshali2: f32 = bakhshali_sqrt(0.0); assert_eq!(bakhshali2, 0.0);
let babylonian1: f32 = babylonian_sqrt(9.0); assert_eq!(babylonian1, 3.0);
let babylonian2: f32 = babylonian_sqrt(0.0); assert_eq!(babylonian2, 0.0);
}
}