Measurement
Area, length, distance and similarity as f64 quantities, each with a certified sign
or zero and a documented bound, and the exact predicates to use when the question is a comparison.
Measurements are f64 values rather than geometric verdicts, so they are approximate by nature.
Each function states what it guarantees: a certified sign (or a certified zero) and a
magnitude whose error is either bounded or, for lengths, measured. Where the real question is “is this
within d?”, an exact predicate answers it, and comparing a measurement with d
does not. None of these functions panics. An input that makes an intermediate result overflow produces a
non-finite f64, never a finite wrong value. None returns a coordinate.
Area
The area functions are in geometres::ops. Each evaluates the shoelace sum with the compensated
accumulator Accum, so the result is as accurate as a computation in
twice the working precision, rounded once. With S the sum of the absolute values of the
shoelace
terms, the compensated result r satisfies the Ogita, Rump and Oishi bound below.
The sign is certified as well. Solving the bound for the error gives
|r − exact| ≤ (ε·|r| + γm2·S) / (1 −
ε), so when |r| exceeds that, the sign of r is the sign of the exact
area. The test uses four times this bound, since a bound too large costs only speed. When |r|
does not exceed it, the sum is redone in exact expansion arithmetic, whose largest component carries the
exact
sign. The same routine decides winding and degeneracy in
Polygon::new.
area
pub fn area(polygon: &Polygon) -> f64
The area of a Polygon: signed_area with no change of sign. Hole placement is
validated at construction and the sign of the sum is certified, so a valid polygon never yields a
negative value.
The absolute value is not taken, because it would only conceal an invalid polygon.
Polygon::new
does not check ring simplicity, so a hole that crosses itself (a spiral, say) can enclose more signed area
than the exterior, and its net signed sum is then negative. That sum is returned rather than made positive
or panicked on: a negative area is a visible sign of an invalid input, which
validate names. An exact zero is reachable too,
through
the one documented limit of the placement check (holes that tile the exterior along collinear shared
edges).
use geometres::ops::area;
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};
let ring = |v: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
// A unit square far from the origin.
let o = 1.0e9;
let square = Polygon::new(ring(&[(o, o), (o + 1.0, o), (o + 1.0, o + 1.0), (o, o + 1.0)]), vec![]).unwrap();
let a = area(&square);
assert!(a > 0.0); // certified sign
assert!((a - 1.0).abs() < 1e-9); // within the compensated bound
// A plain f64 shoelace sum loses every digit to cancellation here.
let v = [(o, o), (o + 1.0, o), (o + 1.0, o + 1.0), (o, o + 1.0)];
let naive: f64 = (0..4)
.map(|i| { let (p, q) = (v[i], v[(i + 1) % 4]); p.0 * q.1 - q.0 * p.1 })
.sum::<f64>() * 0.5;
assert_eq!(naive, 0.0);
signed_area
pub fn signed_area(polygon: &Polygon) -> f64
The signed area of a Polygon, accounting for holes. The exterior ring is counterclockwise
(positive) and each hole clockwise (negative), so the sum is the net area of the region. All rings are
accumulated in one compensated sum rather than rounding each ring’s area first, so
cancellation between a large exterior and a large hole does not lose digits, and the sign of the net area
is
certified as for a single ring.
Polygon::new verifies that every hole lies inside the exterior and that holes are
interior-disjoint, so with the certified sign this function returns a non-negative value for every valid
polygon. A polygon with a self-crossing ring (constructible, invalid) can have a negative net sum. The
result
can be non-finite on overflow.
use geometres::ops::signed_area;
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};
let ring = |v: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
// A 4 x 4 square with a 2 x 2 hole: 16 - 4.
let exterior = ring(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)]);
let hole = ring(&[(1.0, 1.0), (1.0, 3.0), (3.0, 3.0), (3.0, 1.0)]); // clockwise
let polygon = Polygon::new(exterior, vec![hole]).unwrap();
assert_eq!(signed_area(&polygon), 12.0);
signed_area_ring
pub fn signed_area_ring(ring: &LinearRing) -> f64
The signed area of a LinearRing: positive for counterclockwise winding, negative for
clockwise.
The magnitude is the shoelace formula in compensated arithmetic, and the sign is exact:
whenever the compensated result cannot be proven to have the right sign, the sum is redone in exact
expansion arithmetic. Multiplying by 0.5 at the end is exact. If an intermediate product
overflows, the result is non-finite.
use geometres::ops::signed_area_ring;
use geometres::types::{Coord2d, CoordSeq, LinearRing};
let ring = |v: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
let ccw = ring(&[(0.0, 0.0), (3.0, 0.0), (3.0, 4.0)]);
let cw = ring(&[(0.0, 0.0), (3.0, 4.0), (3.0, 0.0)]);
assert_eq!(signed_area_ring(&ccw), 6.0);
assert_eq!(signed_area_ring(&cw), -6.0);
collection_area
pub fn collection_area(collection: &GeometryCollection) -> f64
The sum of the areas of a collection’s polygons, at every depth: each polygon, alone or a part of a
multipolygon, is one term of an Accum sum, in the order the collection’s leaves are
visited. Points and lines contribute no area. Overlapping elements count twice, since a
collection imposes no condition between its elements; where the areal elements are interior-disjoint, the
sum is the area of their union.
Every term is non-negative, so the result is zero if and only if every term is zero: a
collection’s area is zero exactly when it has no non-empty areal element. That positivity rests on
the
area routine’s exactness argument, which assumes its products do not underflow; for coordinates
below
about 2−484 in magnitude that assumption can fail. With
bi each polygon’s own bound and ai its computed
area,
the error of the sum is at most Σbi + (ε +
γk2)·Σai.
use geometres::ops::collection_area;
use geometres::types::{Coord2d, CoordSeq, Geometry, GeometryCollection, LinearRing, Point, Polygon};
let ring = |v: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
let unit = Polygon::new(ring(&[(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]), vec![]).unwrap();
let point = Point::new(Coord2d::new(9.0, 9.0)).unwrap();
// The same square twice counts twice; the point adds nothing.
let collection = GeometryCollection::new(vec![
Geometry::Polygon(unit.clone()),
Geometry::Polygon(unit),
Geometry::Point(point),
]).unwrap();
assert_eq!(collection_area(&collection), 2.0);
// No areal element: exactly zero.
let points = GeometryCollection::new(vec![Geometry::Point(point)]).unwrap();
assert_eq!(collection_area(&points), 0.0);
Length
The length functions are in geometres::ops. Each edge length is f64::hypot, which
avoids the overflow and underflow that sqrt(dx*dx + dy*dy) has for very large or very small
differences, and the edge lengths are added with a compensated sum. Neither step has a proven error
bound in this crate: the result is an approximation, and its accuracy is measured in the test
suite
rather than proven. For that reason the examples below compare against a tolerance rather than an exact
value.
length
pub fn length(line: &LineString) -> f64
The total arc length of a LineString: the sum of the Euclidean distances between consecutive
vertices.
use geometres::ops::length;
use geometres::types::{Coord2d, CoordSeq, LineString};
let line = |v: &[(f64, f64)]| {
LineString::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
// Two legs of a 3-4-5 triangle.
assert!((length(&line(&[(0.0, 0.0), (3.0, 0.0), (3.0, 4.0)])) - 7.0).abs() < 1e-12);
perimeter, ring_perimeter and polygon_length
pub fn perimeter(polygon: &Polygon) -> f64
pub fn ring_perimeter(ring: &LinearRing) -> f64
pub fn polygon_length(polygon: &Polygon) -> f64
Three functions measure a polygon’s boundary, and they differ in which rings they include:
perimeteris the perimeter of the exterior ring alone. Hole rings are not included.ring_perimeteris the perimeter of oneLinearRing, including the closing edge.polygon_lengthis the length of the whole boundary: every edge of every ring, holes included, in one compensated sum. It is positive for every polygon, since each ring has at least three distinct vertices.
use geometres::ops::{perimeter, polygon_length, ring_perimeter};
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};
let ring = |v: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
let close = |a: f64, b: f64| (a - b).abs() < 1e-12;
// A 4 x 4 square with a 2 x 2 hole.
let polygon = Polygon::new(
ring(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)]),
vec![ring(&[(1.0, 1.0), (1.0, 3.0), (3.0, 3.0), (3.0, 1.0)])],
).unwrap();
assert!(close(perimeter(&polygon), 16.0)); // exterior only
assert!(close(ring_perimeter(&polygon.holes()[0]), 8.0));
assert!(close(polygon_length(&polygon), 24.0)); // every ring
edge_length
pub fn edge_length(a: Coord2d, b: Coord2d) -> f64
The length of the edge a → b: hypot of the two coordinate
differences. Approximate, with no certified property. Each difference is rounded once
(exact only when the operands are within a factor of two of each other, by Sterbenz’s lemma), and
the
accuracy of f64::hypot is the platform math library’s, which Rust does not specify, so
no
ulp bound is claimed. A non-finite input gives a non-finite result, and the result is never negative.
length, ring_perimeter and perimeter are compensated sums of this
function.
use geometres::ops::edge_length;
use geometres::types::Coord2d;
let d = edge_length(Coord2d::new(0.0, 0.0), Coord2d::new(3.0, 4.0));
assert!((d - 5.0).abs() < 1e-12);
assert!(edge_length(Coord2d::new(0.0, 0.0), Coord2d::new(f64::INFINITY, 0.0)).is_infinite());
collection_length
pub fn collection_length(collection: &GeometryCollection) -> f64
The sum of the lengths of a collection’s lines and polygon boundaries, at every depth: each line is
one term (length) and each polygon one term (polygon_length, every ring). Points
contribute nothing, and overlapping elements count twice.
The result is zero exactly when the collection has no line or polygon. Its accuracy is measured, not
proven, since the per-term accuracy is; the composition adds at most (ε +
γk2)·Σℓi.
use geometres::ops::collection_length;
use geometres::types::{Coord2d, CoordSeq, Geometry, GeometryCollection, LineString, Point};
let line = LineString::new(CoordSeq::new(vec![Coord2d::new(0.0, 0.0), Coord2d::new(3.0, 4.0)])).unwrap();
let point = Point::new(Coord2d::new(9.0, 9.0)).unwrap();
let collection = GeometryCollection::new(vec![
Geometry::LineString(line.clone()),
Geometry::LineString(line), // counted again
Geometry::Point(point),
]).unwrap();
assert!((collection_length(&collection) - 10.0).abs() < 1e-12);
let points = GeometryCollection::new(vec![Geometry::Point(point)]).unwrap();
assert_eq!(collection_length(&points), 0.0);
Distance
geometres::ops gives two answers about distance, and they answer different questions.
dwithin(a, b, d) decides “is the distance at most d?”
exactly, for every pair of geometries and every finite d ≥ 0.
distance(a, b) returns the distance as an f64, exactly 0.0 if and
only
if the operands intersect and otherwise within a documented bound. Both take any geometry as
&impl Relatable.
Both rest on one decomposition. If the operands intersect, decided by the exact relate
machinery, the distance is 0. Otherwise the distance is attained between boundary elements (the segments of
lines and rings, and isolated points), and between two segments that do not intersect it is attained at an
endpoint of one against the other. Point against segment and point against point are
arithmetica’s
exact predicates. The module documentation gives the proof and the derivation of
the
bound.
distance
pub fn distance(a: &impl Relatable, b: &impl Relatable) -> Result<f64,
GeometryError>
The distance between a and b: exactly 0.0 if and only if
they
intersect, and otherwise a positive f64 within the bound below of the true
distance,
with u = 2−53 and M the largest coordinate magnitude in either
operand. The bound holds whenever every coordinate difference is finite (M ≤
21022 suffices); past that a difference overflows and the affected pair contributes
+∞, never a finite wrong value.
The zero comes from the exact intersection test, not from the arithmetic. For operands that do not
intersect, every computed pair distance could still round to 0.0; a computed 0.0
is then returned as the smallest positive f64, 2−1074, which is
the reason for that term. distance(a, b) <= d is not the answer to “are they
within d?”: within the bound, the comparison can fall on either side of
d. The two are consistent up to it: if dwithin(a, b, d) is false
then
distance(a, b) > d − 64·u·M, and if true then
distance(a, b) < d + 64·u·M.
Errors: GeometryError::EmptyOperand when either operand has no points,
since
the distance to nothing is undefined and 0 would read as contact.
GeometryError::CollectionElementsOverlap for a collection operand whose polygonal leaves
overlap,
as relate refuses it. GeometryError::TooManyEntries for more than
u32::MAX elements on an indexed side.
use geometres::GeometryError;
use geometres::ops::distance;
use geometres::types::{Coord2d, CoordSeq, GeometryCollection, LineString, LinearRing, Point, Polygon};
let square = |x: f64| {
let v = [(x, 0.0), (x + 1.0, 0.0), (x + 1.0, 1.0), (x, 1.0)];
let ring = LinearRing::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap();
Polygon::new(ring, vec![]).unwrap()
};
// Two unit squares 2 apart, and two that share an edge.
let d = distance(&square(0.0), &square(3.0)).unwrap();
let bound = 64.0 * 2f64.powi(-53) * 4.0; // M = 4
assert!((d - 2.0).abs() <= bound);
assert_eq!(distance(&square(0.0), &square(1.0)).unwrap(), 0.0); // touching: exactly zero
// A point 1e-300 above a segment does not touch it, so the distance is not zero.
let point = Point::new(Coord2d::new(0.5, 1e-300)).unwrap();
let segment = LineString::new(CoordSeq::new(vec![Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0)])).unwrap();
assert!(distance(&point, &segment).unwrap() > 0.0);
// The distance to nothing is refused rather than reported as 0.
assert!(matches!(
distance(&point, &GeometryCollection::empty()),
Err(GeometryError::EmptyOperand)
));
dwithin
pub fn dwithin(a: &impl Relatable, b: &impl Relatable, d: f64) ->
Result<bool, GeometryError>
Whether the distance between a and b is at most d, decided
exactly. The result is true when some point of a and some point
of
b lie within d of each other, endpoints and boundaries included;
d = 0
asks whether the geometries intersect. Every decision is an exact predicate, and no distance is
ever
computed. An empty operand gives false.
Errors: GeometryError::InvalidTolerance for a negative or non-finite
d. GeometryError::CollectionElementsOverlap for a collection operand whose
polygonal
leaves overlap, as relate refuses it. GeometryError::TooManyEntries for more
than
u32::MAX elements on an indexed side.
use geometres::ops::dwithin;
use geometres::types::{Coord2d, CoordSeq, LineString, Point};
// A 3-4-5 triangle: the points are exactly 5 apart.
let p = Point::new(Coord2d::new(0.0, 0.0)).unwrap();
let q = Point::new(Coord2d::new(3.0, 4.0)).unwrap();
assert!(dwithin(&p, &q, 5.0).unwrap());
assert!(!dwithin(&p, &q, 5.0_f64.next_down()).unwrap()); // one ulp short
// d = 0 asks whether they intersect: a point 1e-300 off a segment does not.
let point = Point::new(Coord2d::new(0.5, 1e-300)).unwrap();
let segment = LineString::new(CoordSeq::new(vec![Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0)])).unwrap();
assert!(!dwithin(&point, &segment, 0.0).unwrap());
assert!(dwithin(&p, &q, -1.0).is_err()); // invalid tolerance
Similarity
Two discrete similarity measures are in geometres::ops, each as an exact predicate and a
quantity. The predicates (hausdorff_within, frechet_within) decide every
comparison
with an exact arithmetica predicate. The quantities are exactly 0.0 when, and only
when, an exact zero test holds, and otherwise within 64·u·M of the true value,
with
u = 2−53 and M the largest coordinate magnitude in either operand
(for Hausdorff, or 2−1074 if larger). This is the bound of
distance, and it carries through because each measure is built from
maxima and minima of point-to-element distances, and a maximum or minimum of values each within
δ of their true values is within δ of the true maximum or
minimum. Neither measure is densified.
hausdorff_distance
pub fn hausdorff_distance(a: &impl Relatable, b: &impl Relatable) ->
Result<f64, GeometryError>
The discrete Hausdorff distance between a and b: the larger of the two directed
values, where h(a → b) is the largest distance from a vertex of a to the
linework of b. The linework is the segments of lines, the segments of every polygon
ring
(exterior and holes), and isolated points. A polygon is measured by its rings: its interior does
not
count, so a vertex strictly inside a polygon contributes its distance to the nearest ring, not
0.
This is the definition of JTS’s DiscreteHausdorffDistance.
The result is exactly 0.0 if and only if every vertex of each lies on the linework
of
the other, and otherwise an f64 within max(64·u·M,
2−1074) of the true value. For the question “is the Hausdorff distance at most
d?”, use hausdorff_within: if it is false then this value is
greater than d − 64·u·M, and if true then at most d +
64·u·M.
Errors: GeometryError::EmptyOperand when either operand has no points.
GeometryError::TooManyEntries for more than u32::MAX elements on an indexed
side.
use geometres::ops::hausdorff_distance;
use geometres::types::{Coord2d, CoordSeq, LinearRing, Point, Polygon};
let ring = LinearRing::new(CoordSeq::new(vec![
Coord2d::new(0.0, 0.0), Coord2d::new(4.0, 0.0), Coord2d::new(4.0, 4.0), Coord2d::new(0.0, 4.0),
])).unwrap();
let square = Polygon::new(ring, vec![]).unwrap();
let center = Point::new(Coord2d::new(2.0, 2.0)).unwrap();
// The interior does not count: the corners are 2√2 from the center.
let h = hausdorff_distance(¢er, &square).unwrap();
let bound = 64.0 * 2f64.powi(-53) * 4.0; // M = 4
assert!((h - 8.0_f64.sqrt()).abs() <= bound);
hausdorff_within
pub fn hausdorff_within(a: &impl Relatable, b: &impl Relatable, d: f64)
->
Result<bool, GeometryError>
Whether the discrete Hausdorff distance between a and b is at most
d, decided exactly: true when every vertex of a is
within d of the linework of b, and every vertex of b within
d of the linework of a. Each test is an exact arithmetica
predicate,
point to point or point to closed segment. An empty operand gives false.
Errors: GeometryError::InvalidTolerance for a negative or non-finite
d. GeometryError::TooManyEntries for more than u32::MAX elements on
an
indexed side.
use geometres::ops::hausdorff_within;
use geometres::types::{Coord2d, CoordSeq, LineString};
let line = |v: &[(f64, f64)]| {
LineString::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
// Two parallel lines 3 apart.
let a = line(&[(0.0, 0.0), (10.0, 0.0)]);
let b = line(&[(0.0, 3.0), (10.0, 3.0)]);
assert!(hausdorff_within(&a, &b, 3.0).unwrap());
assert!(!hausdorff_within(&a, &b, 3.0_f64.next_down()).unwrap());
frechet_distance
pub fn frechet_distance(a: &LineString, b: &LineString) -> Result<f64,
GeometryError>
The discrete Fréchet distance between the lines a and b, following Eiter
and Mannila. A coupling is a sequence of vertex pairs that starts at the two first vertices, ends
at
the two last, and at each step advances along one line, the other, or both. The distance is the smallest,
over all couplings, of the largest point-to-point distance along the coupling. It is the quantity
JTS’s DiscreteFrechetDistance computes, without densification. Direction
matters: a line and its reverse are at Fréchet distance at least the distance between
its
endpoints, not 0.
The result is exactly 0.0 if and only if the two lines have the same vertices in the
same order, and otherwise an f64 within 64·u·M of the
true
value. For the question “is the Fréchet distance at most d?”, use
frechet_within: if it is false then this value is greater than d −
64·u·M, and if true then at most d + 64·u·M.
Errors: none at present; the Result keeps the signature uniform with the
other distance functions.
use geometres::ops::{frechet_distance, hausdorff_distance};
use geometres::types::{Coord2d, CoordSeq, LineString};
let line = |v: &[(f64, f64)]| {
LineString::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
let a = line(&[(0.0, 0.0), (10.0, 0.0)]);
let reversed = line(&[(10.0, 0.0), (0.0, 0.0)]);
assert_eq!(frechet_distance(&a, &a.clone()).unwrap(), 0.0); // same vertices, same order
// Reversed: the first vertices are coupled, 10 apart. Hausdorff ignores direction.
let bound = 64.0 * 2f64.powi(-53) * 10.0; // M = 10
assert!((frechet_distance(&a, &reversed).unwrap() - 10.0).abs() <= bound);
assert_eq!(hausdorff_distance(&a, &reversed).unwrap(), 0.0);
frechet_within
pub fn frechet_within(a: &LineString, b: &LineString, d: f64) ->
Result<bool, GeometryError>
Whether the discrete Fréchet distance between the lines a and b is at
most
d, decided exactly: true when some coupling keeps every coupled
pair within d. It is Eiter and Mannila’s dynamic program on the grid of vertex pairs,
with
arithmetica’s exact point-to-point predicate deciding each pair, in
O(n·m) time and O(min(n, m)) memory.
Errors: GeometryError::InvalidTolerance for a negative or non-finite
d.
use geometres::ops::frechet_within;
use geometres::types::{Coord2d, CoordSeq, LineString};
let line = |v: &[(f64, f64)]| {
LineString::new(CoordSeq::new(v.iter().map(|&(x, y)| Coord2d::new(x, y)).collect())).unwrap()
};
let a = line(&[(0.0, 0.0), (10.0, 0.0)]);
let b = line(&[(10.0, 0.0), (0.0, 0.0)]);
// Reversed: the first vertices are coupled, 10 apart.
assert!(frechet_within(&a, &b, 10.0).unwrap());
assert!(!frechet_within(&a, &b, 10.0_f64.next_down()).unwrap());
Compensated summation
geometres::accum::Accum is the compensated accumulator behind the area and length sums,
available for a caller’s own sums and dot products. It implements Dot2 (and its special
case Sum2) from T. Ogita, S. M. Rump and S. Oishi, “Accurate Sum and Dot Product”,
SIAM J. Sci. Comput. 26(6), 2005, Algorithm 5.3. Each product is split into the rounded product and
its
exact rounding error, each running-sum step is split the same way, and the rounding errors are accumulated
separately and added once at the end.
Accum
pub struct Accum
A running compensated sum of products and values. It gives an approximate magnitude with a proven
bound, and certifies no sign by itself. After m terms (each add or
add_product is one term), the result r of value satisfies:
That is the accuracy of a computation in twice the working precision, rounded once. When
|exact| is far smaller than Σ|terms|, which is the cancellation this type
exists for, the second term can exceed |exact|, and then the sign of r is not
the
sign of the exact sum. A caller that needs the sign must prove it separately, as the
area functions do.
The bound fails in two places:
- Overflow. The Veltkamp split in
two_productmultiplies by227 + 1, so operands above about1.3e300overflow. The result is then non-finite, never a finite wrong value. - Underflow. When a product’s rounding error underflows (products below about
1e-292) the error term is lost, and the result degrades to a plain sum’s accuracy at that absolute scale.
| Method | What it does |
|---|---|
pub fn new() -> Self |
An empty accumulator: value is 0.0. Accum also implements
Default, Clone and Copy.
|
pub fn add(&mut self, a: f64) |
Adds the plain value a. |
pub fn add_product(&mut self, a: f64, b: f64) |
Adds the product a * b, whose rounding error is captured exactly. |
pub fn value(&self) -> f64 |
The accumulated value, rounded once: within the bound above, and non-finite if any term overflowed. |
pub fn parts(&self) -> (f64, f64) |
The accumulated value as an unevaluated pair (p, s) whose exact sum is the
compensated
value, with s the accumulated rounding errors. Using the pair rather than
value keeps the extra precision for a later product.
|
use geometres::accum::Accum;
// (1e8 + 1)² − 1e16 − 2e8 = 1, but (1e8 + 1)² needs 54 bits and rounds.
let a = 100_000_001.0_f64;
assert_eq!(a * a - 1e16 - 2e8, 0.0); // plain f64 loses the 1
let mut acc = Accum::new();
acc.add_product(a, a); // the product's rounding error is kept
acc.add(-1e16);
acc.add(-2e8);
assert_eq!(acc.value(), 1.0);
// The same value as an unevaluated pair.
let (p, s) = acc.parts();
assert_eq!(p + s, 1.0);