Class Vector2D
- java.lang.Object
-
- org.apache.commons.geometry.euclidean.EuclideanVector<V>
-
- org.apache.commons.geometry.euclidean.MultiDimensionalEuclideanVector<Vector2D>
-
- org.apache.commons.geometry.euclidean.twod.Vector2D
-
- Direct Known Subclasses:
Vector2D.Unit
public class Vector2D extends MultiDimensionalEuclideanVector<Vector2D>
This class represents vectors and points in two-dimensional Euclidean space. Instances of this class are guaranteed to be immutable.
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static class
Vector2D.Sum
Class used to create high-accuracy sums of vectors.static class
Vector2D.Unit
Represents unit vectors.
-
Field Summary
Fields Modifier and Type Field Description static java.util.Comparator<Vector2D>
COORDINATE_ASCENDING_ORDER
Comparator that sorts vectors in component-wise ascending order.static Vector2D
NaN
A vector with all coordinates set to NaN.static Vector2D
NEGATIVE_INFINITY
A vector with all coordinates set to negative infinity.static Vector2D
POSITIVE_INFINITY
A vector with all coordinates set to positive infinity.private double
x
Abscissa (first coordinate).private double
y
Ordinate (second coordinate).static Vector2D
ZERO
Zero vector (coordinates: 0, 0).
-
Constructor Summary
Constructors Modifier Constructor Description private
Vector2D(double x, double y)
Simple constructor.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description Vector2D
add(double factor, Vector2D v)
Add a scaled vector to the instance.Vector2D
add(Vector2D v)
Add a vector to the instance.double
angle(Vector2D v)
Compute the angular separation between two vectors in radians.static Vector2D
centroid(java.lang.Iterable<Vector2D> pts)
Compute the centroid of the given points.static Vector2D
centroid(Vector2D first, Vector2D... more)
Compute the centroid of the given points.private static Vector2D
computeCentroid(Vector2D first, java.util.Iterator<? extends Vector2D> more)
Internal method for computing the centroid of a set of points.private static Vector2D
computeMax(Vector2D first, java.util.Iterator<? extends Vector2D> more)
Internal method for computing a max vector.private static Vector2D
computeMin(Vector2D first, java.util.Iterator<? extends Vector2D> more)
Internal method for computing a min vector.Vector2D.Unit
directionTo(Vector2D v)
Return the unit vector representing the direction of displacement from this vector to the given vector.double
distance(Vector2D v)
Compute the distance between the instance and another vector.double
distanceSq(Vector2D v)
Compute the square of the distance between the instance and another vector.double
dot(Vector2D v)
Compute the dot-product of the instance and another vector.boolean
eq(Vector2D vec, org.apache.commons.numbers.core.Precision.DoubleEquivalence precision)
Return true if the current instance and given vector are considered equal as evaluated by the given precision context.boolean
equals(java.lang.Object other)
Test for the equality of two vector instances.private <T extends Vector2D>
TgetComponent(Vector2D base, boolean reject, DoubleFunction2N<T> factory)
Returns a component of the current instance relative to the given base vector.int
getDimension()
Returns the number of dimensions in the space that this element belongs to.double
getX()
Returns the abscissa (first coordinate value) of the instance.double
getY()
Returns the ordinate (second coordinate value) of the instance.Vector2D
getZero()
Get the zero (null) vector of the space.int
hashCode()
Get a hashCode for the 2D coordinates.boolean
isFinite()
Returns true if all values in this element are finite, meaning they are not NaN or infinite.boolean
isInfinite()
Returns true if any value in this element is infinite and none are NaN; otherwise, returns false.boolean
isNaN()
Returns true if any value in this element is NaN; otherwise returns false.Vector2D
lerp(Vector2D p, double t)
Get a vector constructed by linearly interpolating between this vector and the given vector.static Vector2D
max(java.lang.Iterable<Vector2D> vecs)
Return a vector containing the maximum component values from all input vectors.static Vector2D
max(Vector2D first, Vector2D... more)
Return a vector containing the maximum component values from all input vectors.static Vector2D
min(java.lang.Iterable<Vector2D> vecs)
Return a vector containing the minimum component values from all input vectors.static Vector2D
min(Vector2D first, Vector2D... more)
Return a vector containing the minimum component values from all input vectors.Vector2D
multiply(double a)
Multiply the instance by a scalar.Vector2D
negate()
Get the negation of the instance.double
norm()
Get the L2 norm (commonly known as the Euclidean norm) for the vector.Vector2D.Unit
normalize()
Get a normalized vector aligned with the instance.Vector2D.Unit
normalizeOrNull()
Attempt to compute a normalized vector aligned with the instance, returning null if such a vector cannot be computed.double
normSq()
Get the square of the L2 norm (also known as the Euclidean norm) for the vector.static Vector2D
of(double[] v)
Creates a vector from the coordinates in the given 2-element array.static Vector2D
of(double x, double y)
Returns a vector with the given coordinate values.Vector2D.Unit
orthogonal()
Get a unit vector orthogonal to the instance.Vector2D.Unit
orthogonal(Vector2D dir)
Get a unit vector orthogonal to the current vector and pointing in the direction ofdir
.static Vector2D
parse(java.lang.String str)
Parses the given string and returns a new vector instance.Vector2D
project(Vector2D base)
Get the projection of the instance onto the given base vector.Vector2D
reject(Vector2D base)
Get the rejection of the instance from the given base vector.double
signedArea(Vector2D v)
Compute the signed area of the parallelogram with sides formed by this instance and the given vector.Vector2D
subtract(double factor, Vector2D v)
Subtract a scaled vector from the instance.Vector2D
subtract(Vector2D v)
Subtract a vector from the instance.double[]
toArray()
Get the coordinates for this instance as a dimension 2 array.java.lang.String
toString()
Vector2D
transform(java.util.function.UnaryOperator<Vector2D> fn)
Convenience method to apply a function to this vector.Vector2D
vectorTo(Vector2D v)
Return the vector representing the displacement from this vector to the given vector.Vector2D
withNorm(double magnitude)
Returns a vector with the same direction but with the given norm.-
Methods inherited from class org.apache.commons.geometry.euclidean.EuclideanVector
getCheckedNorm, isZero
-
-
-
-
Field Detail
-
ZERO
public static final Vector2D ZERO
Zero vector (coordinates: 0, 0).
-
NaN
public static final Vector2D NaN
A vector with all coordinates set to NaN.
-
POSITIVE_INFINITY
public static final Vector2D POSITIVE_INFINITY
A vector with all coordinates set to positive infinity.
-
NEGATIVE_INFINITY
public static final Vector2D NEGATIVE_INFINITY
A vector with all coordinates set to negative infinity.
-
COORDINATE_ASCENDING_ORDER
public static final java.util.Comparator<Vector2D> COORDINATE_ASCENDING_ORDER
Comparator that sorts vectors in component-wise ascending order. Vectors are only considered equal if their coordinates match exactly. Null arguments are evaluated as being greater than non-null arguments.
-
x
private final double x
Abscissa (first coordinate).
-
y
private final double y
Ordinate (second coordinate).
-
-
Method Detail
-
getX
public double getX()
Returns the abscissa (first coordinate value) of the instance.- Returns:
- the abscissa
-
getY
public double getY()
Returns the ordinate (second coordinate value) of the instance.- Returns:
- the ordinate
-
toArray
public double[] toArray()
Get the coordinates for this instance as a dimension 2 array.- Returns:
- coordinates for this instance
-
getDimension
public int getDimension()
Returns the number of dimensions in the space that this element belongs to.- Returns:
- the number of dimensions in the element's space
-
isNaN
public boolean isNaN()
Returns true if any value in this element is NaN; otherwise returns false.- Returns:
- true if any value in this element is NaN
-
isInfinite
public boolean isInfinite()
Returns true if any value in this element is infinite and none are NaN; otherwise, returns false.- Returns:
- true if any value in this element is infinite and none are NaN
-
isFinite
public boolean isFinite()
Returns true if all values in this element are finite, meaning they are not NaN or infinite.- Returns:
- true if all values in this element are finite
-
vectorTo
public Vector2D vectorTo(Vector2D v)
Return the vector representing the displacement from this vector to the given vector. This is exactly equivalent tov.subtract(thisVector)
but with a method name that is much easier to visualize.- Specified by:
vectorTo
in classEuclideanVector<Vector2D>
- Parameters:
v
- the vector that the returned vector will be directed toward- Returns:
- vector representing the displacement from this vector to the given vector
-
directionTo
public Vector2D.Unit directionTo(Vector2D v)
Return the unit vector representing the direction of displacement from this vector to the given vector. This is exactly equivalent tov.subtract(thisVector).normalize()
but without the intermediate vector instance.- Specified by:
directionTo
in classEuclideanVector<Vector2D>
- Parameters:
v
- the vector that the returned vector will be directed toward- Returns:
- unit vector representing the direction of displacement from this vector to the given vector
-
lerp
public Vector2D lerp(Vector2D p, double t)
Get a vector constructed by linearly interpolating between this vector and the given vector. The vector coordinates are generated by the equationV = (1 - t)*A + t*B
, whereA
is the current vector andB
is the given vector. This means that ift = 0
, a vector equal to the current vector will be returned. Ift = 1
, a vector equal to the argument will be returned. Thet
parameter is not constrained to the range[0, 1]
, meaning that linear extrapolation can also be performed with this method.- Specified by:
lerp
in classEuclideanVector<Vector2D>
- Parameters:
p
- other vectort
- interpolation parameter- Returns:
- interpolated or extrapolated vector
-
getZero
public Vector2D getZero()
Get the zero (null) vector of the space.- Returns:
- zero vector of the space
-
norm
public double norm()
Get the L2 norm (commonly known as the Euclidean norm) for the vector. This corresponds to the common notion of vector magnitude or length and is defined as the square root of the sum of the squares of all vector components.- Returns:
- L2 norm for the vector
- See Also:
- L2 Norm
-
normSq
public double normSq()
Get the square of the L2 norm (also known as the Euclidean norm) for the vector. This is equal to the sum of the squares of all vector components.- Returns:
- square of the L2 norm for the vector
- See Also:
Vector.norm()
-
withNorm
public Vector2D withNorm(double magnitude)
Returns a vector with the same direction but with the given norm. This is equivalent to callingvec.normalize().scalarMultiply(mag)
but without the intermediate vector.- Parameters:
magnitude
- The vector norm- Returns:
- a vector with the same direction as the current instance but the given norm
-
add
public Vector2D add(Vector2D v)
Add a vector to the instance.- Parameters:
v
- vector to add- Returns:
- a new vector
-
add
public Vector2D add(double factor, Vector2D v)
Add a scaled vector to the instance.- Parameters:
factor
- scale factor to apply to v before adding itv
- vector to add- Returns:
- a new vector
-
subtract
public Vector2D subtract(Vector2D v)
Subtract a vector from the instance.- Parameters:
v
- vector to subtract- Returns:
- a new vector
-
subtract
public Vector2D subtract(double factor, Vector2D v)
Subtract a scaled vector from the instance.- Parameters:
factor
- scale factor to apply to v before subtracting itv
- vector to subtract- Returns:
- a new vector
-
negate
public Vector2D negate()
Get the negation of the instance.- Returns:
- a new vector which is the negation of the instance
-
normalize
public Vector2D.Unit normalize()
Get a normalized vector aligned with the instance. The returned vector has a magnitude of 1.- Returns:
- normalized vector
- See Also:
Vector.normalizeOrNull()
-
normalizeOrNull
public Vector2D.Unit normalizeOrNull()
Attempt to compute a normalized vector aligned with the instance, returning null if such a vector cannot be computed. This method is equivalent toVector.normalize()
but returns null instead of throwing an exception on failure.- Returns:
- normalized vector or null if such a vector cannot be computed, i.e. if the norm is zero, NaN, or infinite
- See Also:
Vector.normalize()
-
multiply
public Vector2D multiply(double a)
Multiply the instance by a scalar.- Parameters:
a
- scalar- Returns:
- a new vector
-
distance
public double distance(Vector2D v)
Compute the distance between the instance and another vector.- Parameters:
v
- second vector- Returns:
- the distance between the instance and v
-
distanceSq
public double distanceSq(Vector2D v)
Compute the square of the distance between the instance and another vector.Calling this method is equivalent to calling:
q.subtract(p).getNormSq()
except that no intermediate vector is built- Parameters:
v
- second vector- Returns:
- the square of the distance between the instance and p
- See Also:
Vector.normSq()
-
dot
public double dot(Vector2D v)
Compute the dot-product of the instance and another vector.- Parameters:
v
- second vector- Returns:
- the dot product (this · v)
-
angle
public double angle(Vector2D v)
Compute the angular separation between two vectors in radians.This method computes the angular separation between the two vectors using the dot product for well separated vectors and the cross product for almost aligned vectors. This allows to have a good accuracy in all cases, even for vectors very close to each other.
- Parameters:
v
- other vector- Returns:
- angular separation between this instance and v in radians
-
project
public Vector2D project(Vector2D base)
Get the projection of the instance onto the given base vector. The returned vector is parallel tobase
. Vector projection and rejection onto a given base are related by the equationv = vprojection + vrejection
- Specified by:
project
in classMultiDimensionalEuclideanVector<Vector2D>
- Parameters:
base
- base vector- Returns:
- the vector projection of the instance onto
base
- See Also:
MultiDimensionalEuclideanVector.reject(MultiDimensionalEuclideanVector)
-
reject
public Vector2D reject(Vector2D base)
Get the rejection of the instance from the given base vector. The returned vector is orthogonal tobase
. This operation can be interpreted as returning the orthogonal projection of the instance onto the hyperplane orthogonal tobase
. Vector projection and rejection onto a given base are related by the equationv = vprojection + vrejection
- Specified by:
reject
in classMultiDimensionalEuclideanVector<Vector2D>
- Parameters:
base
- base vector- Returns:
- the vector rejection of the instance from
base
- See Also:
MultiDimensionalEuclideanVector.project(MultiDimensionalEuclideanVector)
-
orthogonal
public Vector2D.Unit orthogonal()
Get a unit vector orthogonal to the instance. The returned vector is computed by rotating the current instancepi/2
radians counterclockwise around the origin and normalizing. For example, if this method is called on a vector pointing along the positive x-axis, then a unit vector representing the positive y-axis is returned.- Specified by:
orthogonal
in classMultiDimensionalEuclideanVector<Vector2D>
- Returns:
- a unit vector orthogonal to the current instance
- Throws:
java.lang.IllegalArgumentException
- if the norm of the current instance is zero, NaN, or infinite
-
orthogonal
public Vector2D.Unit orthogonal(Vector2D dir)
Get a unit vector orthogonal to the current vector and pointing in the direction ofdir
. This method is equivalent to callingdir.reject(vec).normalize()
except that no intermediate vector object is produced.- Specified by:
orthogonal
in classMultiDimensionalEuclideanVector<Vector2D>
- Parameters:
dir
- the direction to use for generating the orthogonal vector- Returns:
- unit vector orthogonal to the current vector and pointing in the direction of
dir
that does not lie along the current vector
-
signedArea
public double signedArea(Vector2D v)
Compute the signed area of the parallelogram with sides formed by this instance and the given vector.The parallelogram in question can be visualized by taking the current instance as the first side and placing
v
at the end of it to create the second. The other sides are formed by lines parallel to these two vectors. Ifv
points to the left of the current instance (ie, the parallelogram is wound counter-clockwise), then the returned area is positive. Ifv
points to the right of the current instance, (ie, the parallelogram is wound clockwise), then the returned area is negative. If the vectors are collinear (ie, they lie on the same line), then 0 is returned. The area of the triangle formed by the two vectors is exactly half of the returned value.- Parameters:
v
- vector representing the second side of the constructed parallelogram- Returns:
- the signed area of the parallelogram formed by this instance and the given vector
-
transform
public Vector2D transform(java.util.function.UnaryOperator<Vector2D> fn)
Convenience method to apply a function to this vector. This can be used to transform the vector inline with other methods.- Parameters:
fn
- the function to apply- Returns:
- the transformed vector
-
eq
public boolean eq(Vector2D vec, org.apache.commons.numbers.core.Precision.DoubleEquivalence precision)
Return true if the current instance and given vector are considered equal as evaluated by the given precision context.Equality is determined by comparing each pair of components in turn from the two vectors. If all components evaluate as equal, then the vectors are considered equal. If any are not equal, then the vectors are not considered equal. Note that this approach means that the calculated distance between two "equal" vectors may be as much as
√(n * eps2)
, wheren
is the number of components in the vector andeps
is the maximum epsilon value allowed by the precision context.- Specified by:
eq
in classEuclideanVector<Vector2D>
- Parameters:
vec
- vector to check for equalityprecision
- precision context used to determine floating point equality- Returns:
- true if the current instance is considered equal to the given vector when using the given precision context; otherwise false
-
hashCode
public int hashCode()
Get a hashCode for the 2D coordinates.All NaN values have the same hash code.
- Overrides:
hashCode
in classjava.lang.Object
- Returns:
- a hash code value for this object
-
equals
public boolean equals(java.lang.Object other)
Test for the equality of two vector instances.If all coordinates of two vectors are exactly the same, and none are
Double.NaN
, the two instances are considered to be equal.NaN
coordinates are considered to globally affect the vector and be equal to each other - i.e, if either (or all) coordinates of the vector are equal toDouble.NaN
, the vector is equal toNaN
.- Overrides:
equals
in classjava.lang.Object
- Parameters:
other
- Object to test for equality to this- Returns:
- true if two Vector2D objects are equal, false if object is null, not an instance of Vector2D, or not equal to this Vector2D instance
-
toString
public java.lang.String toString()
- Overrides:
toString
in classjava.lang.Object
-
getComponent
private <T extends Vector2D> T getComponent(Vector2D base, boolean reject, DoubleFunction2N<T> factory)
Returns a component of the current instance relative to the given base vector. Ifreject
is true, the vector rejection is returned; otherwise, the projection is returned.- Type Parameters:
T
- Vector implementation type- Parameters:
base
- The base vectorreject
- If true, the rejection of this instance frombase
is returned. If false, the projection of this instance ontobase
is returned.factory
- factory function used to build the final vector- Returns:
- The projection or rejection of this instance relative to
base
, depending on the value ofreject
. - Throws:
java.lang.IllegalArgumentException
- ifbase
has a zero, NaN, or infinite norm
-
of
public static Vector2D of(double x, double y)
Returns a vector with the given coordinate values.- Parameters:
x
- abscissa (first coordinate value)y
- abscissa (second coordinate value)- Returns:
- vector instance
-
of
public static Vector2D of(double[] v)
Creates a vector from the coordinates in the given 2-element array.- Parameters:
v
- coordinates array- Returns:
- new vector
- Throws:
java.lang.IllegalArgumentException
- if the array does not have 2 elements
-
parse
public static Vector2D parse(java.lang.String str)
Parses the given string and returns a new vector instance. The expected string format is the same as that returned bytoString()
.- Parameters:
str
- the string to parse- Returns:
- vector instance represented by the string
- Throws:
java.lang.IllegalArgumentException
- if the given string has an invalid format
-
max
public static Vector2D max(Vector2D first, Vector2D... more)
Return a vector containing the maximum component values from all input vectors.- Parameters:
first
- first vectormore
- additional vectors- Returns:
- a vector containing the maximum component values from all input vectors
-
max
public static Vector2D max(java.lang.Iterable<Vector2D> vecs)
Return a vector containing the maximum component values from all input vectors.- Parameters:
vecs
- input vectors- Returns:
- a vector containing the maximum component values from all input vectors
- Throws:
java.lang.IllegalArgumentException
- if the argument does not contain any vectors
-
computeMax
private static Vector2D computeMax(Vector2D first, java.util.Iterator<? extends Vector2D> more)
Internal method for computing a max vector.- Parameters:
first
- first vectormore
- iterator with additional vectors- Returns:
- vector containing the maximum component values of all input vectors
-
min
public static Vector2D min(Vector2D first, Vector2D... more)
Return a vector containing the minimum component values from all input vectors.- Parameters:
first
- first vectormore
- more vectors- Returns:
- a vector containing the minimum component values from all input vectors
-
min
public static Vector2D min(java.lang.Iterable<Vector2D> vecs)
Return a vector containing the minimum component values from all input vectors.- Parameters:
vecs
- input vectors- Returns:
- a vector containing the minimum component values from all input vectors
- Throws:
java.lang.IllegalArgumentException
- if the argument does not contain any vectors
-
computeMin
private static Vector2D computeMin(Vector2D first, java.util.Iterator<? extends Vector2D> more)
Internal method for computing a min vector.- Parameters:
first
- first vectormore
- iterator with additional vectors- Returns:
- vector containing the minimum component values of all input vectors
-
centroid
public static Vector2D centroid(Vector2D first, Vector2D... more)
Compute the centroid of the given points. The centroid is the arithmetic mean position of a set of points.- Parameters:
first
- first pointmore
- additional points- Returns:
- the centroid of the given points
-
centroid
public static Vector2D centroid(java.lang.Iterable<Vector2D> pts)
Compute the centroid of the given points. The centroid is the arithmetic mean position of a set of points.- Parameters:
pts
- the points to compute the centroid of- Returns:
- the centroid of the given points
- Throws:
java.lang.IllegalArgumentException
- if the argument contains no points
-
-