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
use num_traits::{real::Real};
use std::ops::{Range, RangeInclusive};
use crate::{LinSpace, Linear, lin_space, map::{Map, Function}};
pub fn log_space<R, T>(range: R, steps: usize) -> LogSpace<T>
where
R: IntoLogSpace<T>,
{
range.into_log_space(steps)
}
pub trait IntoLogSpace<T> {
fn into_log_space(self, steps: usize) -> LogSpace<T>;
}
impl<T> IntoLogSpace<T> for RangeInclusive<T>
where
T: Linear + Real,
{
fn into_log_space(self, steps: usize) -> LogSpace<T> {
let (a, b) = self.into_inner();
Map::new(lin_space(a.log2()..=b.log2(), steps), Exp2)
}
}
impl<T> IntoLogSpace<T> for Range<T>
where
T: Linear + Real,
{
fn into_log_space(self, steps: usize) -> LogSpace<T> {
let Range { start: a, end: b } = self;
Map::new(lin_space(a.log2()..b.log2(), steps), Exp2)
}
}
pub struct Exp2;
impl<T> Function<T> for Exp2 where T: Real {
type Output = T;
#[inline]
fn call(&self, x: T) -> Self::Output {
x.exp2()
}
}
pub type LogSpace<T> = Map<LinSpace<T>, Exp2>;
#[cfg(test)]
mod tests {
use super::*;
use itertools::zip_eq;
#[test]
fn test_log_space_inclusive() {
let it = log_space(1.0..=1000.0, 4);
let expected: Vec<f64> = vec![1.0, 10.0, 100.0, 1000.0];
assert!(zip_eq(it, expected).all(|(x, y)| (x-y).abs() < 1e-10));
}
#[test]
fn test_log_space_exclusive() {
let it = log_space(1.0..1000.0, 3);
let expected: Vec<f64> = vec![1.0, 10.0, 100.0];
assert!(zip_eq(it, expected).all(|(x, y)| (x-y).abs() < 1e-10));
}
}