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
// SPDX-FileCopyrightText: 2025 Helge Eichhorn <git@helgeeichhorn.de>
//
// SPDX-License-Identifier: MPL-2.0
//! General-purpose utilities.
/// An iterator that yields `n` evenly spaced values from `start` to `end` (inclusive).
pub struct Linspace {
start: f64,
end: f64,
n: usize,
current: usize,
}
impl Linspace {
/// Creates a new `Linspace` iterator with `n` points from `start` to `end`.
pub fn new(start: f64, end: f64, n: usize) -> Self {
Self {
start,
end,
n,
current: 0,
}
}
}
impl Iterator for Linspace {
type Item = f64;
fn next(&mut self) -> Option<Self::Item> {
if self.current >= self.n {
return None;
}
let value = if self.n == 1 {
self.start
} else {
let t = self.current as f64 / (self.n - 1) as f64;
self.start + t * (self.end - self.start)
};
self.current += 1;
Some(value)
}
fn size_hint(&self) -> (usize, Option<usize>) {
let remaining = self.n - self.current;
(remaining, Some(remaining))
}
}
impl ExactSizeIterator for Linspace {}