Skip to content

Commit 37d96f5

Browse files
committed
Better f64 algorithm handles the float point error
1 parent 3ebdc96 commit 37d96f5

File tree

1 file changed

+10
-2
lines changed

1 file changed

+10
-2
lines changed

plotters/src/coord/ranged1d/types/numeric.rs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,10 +124,15 @@ macro_rules! gen_key_points_comp {
124124
// By default, we make the granularity as the 1/10 of the scale.
125125
let mut value_granularity = scale / 10.0;
126126
fn rem_euclid(a: f64, b: f64) -> f64 {
127-
if b > 0.0 {
127+
let ret = if b > 0.0 {
128128
a - (a / b).floor() * b
129129
} else {
130130
a - (a / b).ceil() * b
131+
};
132+
if (ret - b).abs() < std::f64::EPSILON {
133+
0.0
134+
} else {
135+
ret
131136
}
132137
}
133138

@@ -174,7 +179,7 @@ macro_rules! gen_key_points_comp {
174179
let left_base = (left / value_granularity).floor() * value_granularity;
175180
let mut left_relative = left - left_base;
176181
let right = range.1 - rem_euclid(range.1, scale);
177-
while left_relative <= right - left_base {
182+
while (right - left_relative - left_base) >= -std::f64::EPSILON {
178183
let new_left_relative = (left_relative / value_granularity).round() * value_granularity;
179184
if new_left_relative < 0.0 {
180185
left_relative += value_granularity;
@@ -423,5 +428,8 @@ mod test {
423428
let coord: RangedCoordf64 = (1.0..125.0).into();
424429
let points = coord.key_points(12);
425430
assert_eq!(points.len(), 12);
431+
let coord: RangedCoordf64 = (0.9995..1.0005).into();
432+
let points = coord.key_points(11);
433+
assert_eq!(points.len(), 11);
426434
}
427435
}

0 commit comments

Comments
 (0)