forked from Axect/Peroxide
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useful.rs
124 lines (112 loc) · 2.54 KB
/
useful.rs
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
121
122
123
124
//! Useful missing tools
use std::convert;
use std::f64::MAX;
// =============================================================================
// Fundamental Utils
// =============================================================================
/// Near equal
///
/// # Examples
/// ```
/// extern crate peroxide;
/// use peroxide::fuga::*;
///
/// assert!(nearly_eq(1.0/3.0 * 3.0, 1));
/// ```
pub fn nearly_eq<S, T>(x: S, y: T) -> bool
where
S: convert::Into<f64>,
T: convert::Into<f64>,
{
let mut b: bool = false;
let e = 1e-7;
let p: f64 = x.into().abs();
let q: f64 = y.into().abs();
if (p - q).abs() < e {
b = true;
} else if (p - q).abs() / (p + q).min(MAX) < e {
b = true;
}
b
}
#[allow(unused_comparisons)]
pub fn tab(s: &str, space: usize) -> String {
let l = s.len();
let mut m: String = String::new();
let fs = format!("{}{}", " ".repeat(space - l), s);
m.push_str(&fs);
return m;
}
pub fn quot_rem(x: usize, y: usize) -> (i32, i32) {
((x / y) as i32, (x % y) as i32)
}
// =============================================================================
// Choose Utils
// =============================================================================
pub fn choose_shorter_string(x1: String, x2: String) -> String {
if x1.len() > x2.len() {
x2
} else {
x1
}
}
pub fn choose_shorter_vec(x1: &Vec<f64>, x2: &Vec<f64>) -> Vec<f64> {
if x1.len() > x2.len() {
x2.clone()
} else {
x1.clone()
}
}
pub fn choose_longer_vec(x1: &Vec<f64>, x2: &Vec<f64>) -> Vec<f64> {
if x1.len() <= x2.len() {
x2.clone()
} else {
x1.clone()
}
}
pub fn max<T>(v: Vec<T>) -> T
where
T: PartialOrd + Copy + Clone,
{
let l = v.len();
if l == 1 {
v[0]
} else {
let mut t = if v[0] >= v[1] { v[0] } else { v[1] };
for i in 2..v.len() {
if v[i] > t {
t = v[i];
}
}
t
}
}
pub fn min<T>(v: Vec<T>) -> T
where
T: PartialOrd + Copy + Clone,
{
let l = v.len();
if l == 1 {
v[0]
} else {
let mut t = if v[0] <= v[1] { v[0] } else { v[1] };
for i in 2..v.len() {
if v[i] < t {
t = v[i];
}
}
t
}
}
/// Signum function
pub fn sgn(x: usize) -> f64 {
if x % 2 == 0 {
1f64
} else {
-1f64
}
}
/// Vector compare
pub fn eq_vec(x: &Vec<f64>, y: &Vec<f64>, tol: f64) -> bool {
x.iter().zip(y.iter()).all(|(x, y)| (x - y).abs() <= tol)
}