Skip to content

Instantly share code, notes, and snippets.

@alfonmga
Created July 6, 2021 16:02
Show Gist options
  • Save alfonmga/c670f08260b6d4cdace3294ff30f4644 to your computer and use it in GitHub Desktop.
Save alfonmga/c670f08260b6d4cdace3294ff30f4644 to your computer and use it in GitHub Desktop.
Rust: Iterator over floating-point range
struct FRange {
val: f64,
end: f64,
incr: f64
}
fn range(x1: f64, x2: f64, skip: f64) -> FRange {
FRange {val: x1, end: x2, incr: skip}
}
impl Iterator for FRange {
type Item = f64;
fn next(&mut self) -> Option<Self::Item> {
let res = self.val;
if res >= self.end {
None
} else {
self.val += self.incr;
Some(res)
}
}
}
fn main() {
for x in range(0.0, 1.0, 0.1) {
println!("{} ", x);
}
}
@alfonmga
Copy link
Author

alfonmga commented Jul 6, 2021

Output result:

0 
0.1 
0.2 
0.30000000000000004 
0.4 
0.5 
0.6 
0.7 
0.7999999999999999 
0.8999999999999999 
0.9999999999999999 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment