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
use super::misc::ToFloat;
use std::ops::{Add, Sub, Div, Mul};
pub struct Linspace<F> {
start: F,
step: F,
index: usize,
len: usize,
}
impl<F> Iterator for Linspace<F>
where F: Copy + Add<Output=F> + Mul<Output=F>,
usize: ToFloat<F>,
{
type Item = F;
#[inline]
fn next(&mut self) -> Option<F> {
if self.index >= self.len {
None
} else {
let i = self.index;
self.index += 1;
Some(self.start + self.step * i.to_float())
}
}
#[inline]
fn size_hint(&self) -> (usize, Option<usize>) {
let n = self.len - self.index;
(n, Some(n))
}
}
impl<F> DoubleEndedIterator for Linspace<F>
where F: Copy + Add<Output=F> + Mul<Output=F>,
usize: ToFloat<F>,
{
#[inline]
fn next_back(&mut self) -> Option<F> {
if self.index >= self.len {
None
} else {
self.len -= 1;
let i = self.len;
Some(self.start + self.step * i.to_float())
}
}
}
impl<F> ExactSizeIterator for Linspace<F> where Linspace<F>: Iterator { }
#[inline]
pub fn linspace<F>(a: F, b: F, n: usize) -> Linspace<F> where
F: Copy + Sub<Output=F> + Div<Output=F> + Mul<Output=F>,
usize: ToFloat<F>,
{
let step = if n > 1 {
let nf: F = n.to_float();
(b - a)/(nf - 1.to_float())
} else {
0.to_float()
};
Linspace {
start: a,
step: step,
index: 0,
len: n,
}
}