pub trait LinearInterpolation<Point, Input> {
// Required method
fn linear_interpolate(&self, x: Input) -> Result<Point, InterpolationError>;
}Expand description
A trait that provides functionality for performing linear interpolation.
§Overview
The LinearInterpolation trait defines the behavior for linearly interpolating
values along a curve or dataset. It allows implementors to compute the interpolated
point for a given input using linear methods.
Linear interpolation is a simple and widely-used technique in which new data points can be estimated within the range of a discrete set of known data points by connecting adjacent points with straight lines.
§Associated Types
Point: Represents the type of the interpolated data point (e.g., coordinates, numerical values, or other types).Input: Represents the type of the input value used to calculate the interpolation (e.g., a single number such as anf64or a high-precision number likeDecimal).Error: Defines the error type returned if interpolation cannot be performed due to invalid input or other constraints (e.g., insufficient points for interpolation).
§Required Method
§linear_interpolate
This method calculates the interpolated value for a given input.
-
Input:
Requires a value of typeInput(e.g., a numerical value or coordinate) for which the corresponding interpolatedPointshould be calculated. -
Returns:
- On success, returns a
Resultcontaining the interpolated value of typePoint. - On failure, returns a
Resultcontaining an error of typeSelf::Errorthat describes the reason for failure (e.g., invalid input or insufficient data points).
- On success, returns a
§Typical Usage
This trait is abstract and should be implemented for data structures representing curves or data sets where linear interpolation is required. Examples include interpolating between points on a 2D curve, estimating values in a time series, or refining graphical data.
§Example Use Case (General)
This trait can be used to:
- Estimate missing values in a dataset.
- Provide smooth transitions between adjacent points on a graph.
- Implement real-time interpolations for dynamic systems, such as animations or simulations.
§Notes on Implementation
-
Implementors of this trait must ensure that the interpolation logic respects the shape and constraints of the data being used. This involves:
- Validating input values.
- Handling boundary conditions (e.g., extrapolation or edge points).
-
High precision or custom input/output types (e.g.,
Decimal) can be used when necessary to avoid issues related to floating-point errors in sensitive calculations.
§Example Implementation Outline
- Access two known points adjacent to the input value.
- Compute the slope and intercept of the line between the two points.
- Evaluate the equation of the line at the given input to determine the interpolated point.
§Errors
When implementing this trait, common errors that may be returned include:
- Insufficient data points for interpolation.
- Out-of-bounds input values or indices.
- Invalid data point structures or internal state errors.
§See Also
crate::geometrics::CubicInterpolation: An alternative interpolation method using cubic polynomials.crate::geometrics::InterpolationType: Enum representing supported interpolation methods in the library.
The LinearInterpolation trait is part of a modular design and is often re-exported
in higher-level library components for ease of use.
§One point per abscissa
Every interpolator here reads its sample as a function of the abscissa:
at most one ordinate per x. See
Curve::new for the rule and for why no
constructor enforces it. A sample carrying several ordinates at one
abscissa is outside the contract, and the answer is
InterpolationError::DegenerateInterval, never one of the stacked
ordinates chosen silently: the bracket around a repeated abscissa has
zero width and the slope across it is undefined. A projection of a
surface is multi-valued by construction, which is why
Surface::project_onto returns a
Vec<Point2D> and not a curve; aggregate it before interpolating.
Required Methods§
Sourcefn linear_interpolate(&self, x: Input) -> Result<Point, InterpolationError>
fn linear_interpolate(&self, x: Input) -> Result<Point, InterpolationError>
Performs linear interpolation for a given input value.
§Parameters
x: The input value of typeInputfor which the interpolated point should be calculated.
§Returns
Ok(Point): The calculated interpolated value of typePoint.Err(Self::Error): An error indicating the reason why interpolation failed.
§Errors
Returns InterpolationError::EmptyData when the sample is
empty, InterpolationError::OutOfRange when x falls
outside the sample domain, and
InterpolationError::DegenerateInterval when two
bracketing samples share the same x coordinate.
Dyn Compatibility§
This trait is dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety".
Implementors§
impl LinearInterpolation<Point2D, Decimal> for Curve
Implements the LinearInterpolation trait for the Curve struct.
This implementation provides linear interpolation functionality for a given set
of points on a curve. The interpolation computes the y value corresponding
to a given x value using the linear interpolation formula. The method ensures
that the input x is within the range of the curve’s defined points.
y = p1.y + (x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x)§Parameters
x: ADecimalrepresenting thex-coordinate for which the corresponding interpolatedyvalue is to be computed.
§Returns
Ok(Point2D): APoint2Dinstance containing the inputxvalue and the interpolatedyvalue.Err(CurvesError): Returns an error of typeCurvesError::InterpolationErrorin any of the following cases:- The curve does not have enough points for interpolation.
- The provided
xvalue is outside the range of the curve’s points. - Bracketing points for
xcannot be found.
§Working Mechanism
- The method calls
find_bracket_points(implemented in theInterpolatetrait) to locate the index pair(i, j)of two points that bracket thexvalue. - From the located points
p1andp2, the method calculates the interpolatedyvalue using the linear interpolation formula. - Finally, a
Point2Dis created and returned with the providedxand the computedyvalue.
§Implementation Details
- The function leverages
Decimalarithmetic for high precision in calculations. - It assumes that the provided points on the curve are sorted in ascending order
based on their
xvalues.
§Errors
This method returns a CurvesError in the following cases:
- Insufficient Points: When the curve has fewer than two points.
- Out-of-Range
x: When the inputxvalue lies outside the range of the defined points. - No Bracketing Points Found: When the method fails to find two points
that bracket the given
x. - Degenerate Bracket: When several points share the requested
abscissa. The curve has no value there and the bracket around it has
zero width, so the method reports
InterpolationError::DegenerateIntervalinstead of picking one of the ordinates stacked there.
§One point per abscissa
A curve is a function of its abscissa; see Curve::new. Asking for a
repeated abscissa returns InterpolationError::DegenerateInterval; no
ordinate of the stack is chosen.
Away from the stack the method still answers, reading the stack as a
vertical jump: an x strictly inside an interval bounded by a repeated
abscissa brackets against the point on its own side, the highest
ordinate when the stack bounds the interval on the left and the lowest
when it bounds it on the right.
§Example (How it works internally)
Suppose the curve is defined by the following points:
p1 = (2.0, 4.0)p2 = (5.0, 10.0)
Given x = 3.0, the method computes:
y = 4.0 + (3.0 - 2.0) * (10.0 - 4.0) / (5.0 - 2.0)
= 4 + 1 * 6 / 3
= 4 + 2
= 6.0It will return Point2D { x: 3.0, y: 6.0 }.
§See Also
find_bracket_points: Finds two points that bracket a value.Point2D: Represents points in 2D space.CurvesError: Represents errors related to curve operations.
impl LinearInterpolation<Point3D, Point2D> for Surface
§Linear Interpolation for Surfaces
Implementation of the LinearInterpolation trait for Surface structures, enabling
interpolation from 2D points to 3D points using barycentric coordinates.
§Overview
This implementation allows calculating the height (z-coordinate) of any point within the surface’s x-y range by using linear interpolation based on the three nearest points in the surface. The method employs barycentric coordinate interpolation with triangulation of the nearest points.
§Algorithm
The interpolation process follows these steps:
- Validate that the input point is within the surface’s range
- Check for degenerate cases (all points at same location)
- Check for exact matches with existing points
- Find the three nearest points to the query point
- Calculate barycentric coordinates for the triangle formed by these points
- Interpolate the z-value using the barycentric weights