Math::...::Real(3pm)

πŸ“¦
version 0.18 Β· 3 versions
, in ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ¦‹ Math::Vector::Real β€” real vector arithmetic in Perl πŸ’–

okay so bestie. this is Math::Vector::Real, living in the User Contributed Perl Documentation (aka the 3pm shelf of your man pages), and it is exactly what it sounds like: a little pure-perl module that lets you do real vector arithmetic in any dimension you want. no cap.


✨ SYNOPSIS ✨

use Math::Vector::Real;

my $v = V(1.1, 2.0, 3.1, -4.0, -12.0);
my $u = V(2.0, 0.0, 0.0,  1.0,   0.3);

printf "abs(%s) = %d\n", $v, abs($b);
my $dot = $u * $v;
my $sub = $u - $v;
# etc...

🌸 DESCRIPTION 🌸

It's a simple, pure Perl module for manipulating vectors of any dimension. any. dimension. she doesn't gatekeep. πŸ’…

The function V, which the module always exports (so it's just there, no asking), is how you make new vectors:

my $v = V(0, 1, 3, -1);

Vectors are represented as blessed array references. You're allowed to poke at those arrays directly β€” as long as the only things you put in them are real numbers. (Well, technically integers are fine too, because mathematically speaking, integers are a subset of the real numbers. she said what she said. πŸŽ€)

Example:

my $v = V(0.0, 1.0);

# extending the 2D vector to 3D:
push @$v, 0.0;

# setting some component value:
$v->[0] = 23;

Vectors can be dropped straight into mathematical expressions:

my $u = V(3, 3, 0);
$p = $u * $v;       # dot product
$f = 1.4 * $u + $v; # scalar product and vector addition
$c = $u x $v;       # cross product, only defined for 3D vectors
# etc.

The operations currently supported are:

+ * /
- (both unary and binary)
x (cross product for 3D vectors)
+= -= *= /= x=
== !=
"" (stringfication)
abs (returns the norm)
atan2 (returns the angle between two vectors)

And that, AFAIK, is everything you can throw at a vector. that's the whole menu. and it ate. πŸ”₯

When an array reference gets used in an operation that involves a vector, it gets automatically upgraded to a vector. like it just knows. for instance:

my $v = V(1, 2);
$v += [0, 2];

🧚 Extra methods 🧚

Besides the common mathematical operations up above, the package also hands you these methods.

Heads up bestie: all of these methods are non-destructive β€” they return brand new objects with the result. nobody is getting mutated behind your back. (except the two that literally say they're destructive, iykyk 😭)

$v = Math::Vector::Real->new(@components)

Same energy as V(@components). literally equivalent, no notes.

$zero = Math::Vector::Real->zero($dim)

Gives you the zero vector of the dimension you asked for.

$v = Math::Vector::Real->cube($dim, $size)

Gives you a vector of the given dimension where every single component is set to $size.

$u = Math::Vector::Real->axis_versor($dim, $ix)

Gives you a unitary vector of the given dimension, parallel to the axis with index $ix (0-based, so first axis is 0, not 1, ok πŸ’…).

For instance:

Math::Vector::Real->axis_versor(5, 3); # V(0, 0, 0, 1, 0)
Math::Vector::Real->axis_versor(2, 0); # V(1, 0)

@b = Math::Vector::Real->canonical_base($dim)

Returns the canonical base for the vector space of the given dimension.

$u = $v->versor

Returns the versor for the given vector. it's the same thing as:

$u = $v / abs($v);

$wrapped = $w->wrap($v)

Returns the result of wrapping the given vector inside the box (hyper-cube) defined by $w.

Long description (she does not abbreviate, and honestly? iconic):

Given the vector W and the canonical base U1, U2, ...Un such that W = w1*U1 + w2*U2 +...+ wn*Un. For every component wi we can consider the infinite set of affine hyperplanes perpendicular to Ui such that they contain the point j * wi * Ui being j an integer number.

The combination of all the hyperplanes defined by every component define a grid that divides the space into an infinite set of affine hypercubes. Every hypercube can be identified by its lower corner indexes j1, j2, ..., jN or its lower corner point j1*w1*U1 + j2*w2*U2 +...+ jn*wn*Un.

Given the vector V, wrapping it by W is equivalent to finding where it lays relative to the lower corner point of the hypercube inside the grid containing it:

Wrapped = V - (j1*w1*U1 + j2*w2*U2 +...+ jn*wn*Un)

such that ji*wi <= vi <  (ji+1)*wi

$max = $v->max_component

Returns the maximum of the absolute values of the vector components.

$min = $v->min_component

Returns the minimum of the absolute values of the vector components.

$d2 = $b->norm2

Returns the norm of the vector, squared. (yes, it's called $b in the docs. she's quirky. we love her.)

$d = $v->dist($u)

Returns the distance between the two vectors.

$d = $v->dist2($u)

Returns the distance between the two vectors, squared.

$d = $v->manhattan_norm

Returns the norm of the vector computed with the Manhattan metric. πŸ™οΈ

$d = $v->manhattan_dist($u)

Returns the distance between the two vectors using the Manhattan metric.

$d = $v->chebyshev_norm

Returns the norm of the vector computed with the Chebyshev metric. (note that this method is just an alias for max_component.)

$d = $v->chebyshev_dist($u)

Returns the distance between the two vectors using the Chebyshev metric.

($bottom, $top) = Math::Vector::Real->box($v0, $v1, $v2, ...)

Returns the two corners of the axis-aligned minimum bounding box (http://en.wikipedia.org/wiki/Minimum_bounding_box#Axis-aligned_minimum_bounding_box) β€” or hyperrectangle (http://en.wikipedia.org/wiki/Hyperrectangle) β€” for all the given vectors.

In scalar context, it returns the difference between the two corners instead (aka the box diagonal vector).

$p = $v->nearest_in_box($w0, $w1, ...)

Returns the vector nearest to $v from the axis-aligned minimum box bounding the given set of vectors.

For instance, if you have a point $v and an axis-aligned rectangle defined by two opposite corners ($c0 and $c1), you can use this method to find the point nearest to $v from inside the rectangle:

my $n = $v->nearest_in_box($c0, $c1);
Note that if $v lays inside the box, the nearest point is $v itself. otherwise it's gonna be some point on the box hyper-surface. she's honest about it.

$d2 = $v->dist2_to_box($w0, $w1, ...)

Calculates the square of the minimal distance between the vector $v and the minimal axis-aligned box containing all the vectors ($w0, $w1, ...).

$d2 = $v->max_dist2_to_box($w0, $w1, ...)

Calculates the square of the maximum distance between the vector $v and the minimal axis-aligned box containing all the vectors ($w0, $w1, ...).

$d = $v->chebyshev_dist_to_box($w0, $w1, ...)

Calculates the minimal distance between the vector $v and the minimal axis-aligned box containing all the vectors ($w0, $w1, ...) using the Chebyshev metric.

$d2 = Math::Vector::Real->dist2_between_boxes($a0, $a1, $b0, $b1)

Returns the square of the minimum distance</b> between any two points belonging to the boxes defined by ($a0, $a1) and ($b0, $b1) respectively.

$d2 = Math::Vector::Real->max_dist2_between_boxes($a0, $a1, $b0, $b1)

Returns the square of the maximum distance between any two points belonging respectively to the boxes defined by ($a0, $a1) and ($b0, $b1).

$d2 = $v->dist2_to_segment($a0, $a1)

Returns the square of the minimum distance between the given point $v and the line segment defined by the vertices $a0 and $a1.

$d2 = Math::Vector::Real->dist2_between_segments($a0, $a1, $b0, $b1)

Returns the square of the distance between the line segment defined by the vertices $a0 and $a1 and the one defined by the vertices $b0 and $b1.

⚠️ Degenerated cases where the length of any segment is (too close to) 0 are not supported. she said don't even try it.

$v->set($u)

Equivalent to $v = $u, but without allocating a new object. efficient queen.

Note that this method is destructive. 🫣

$d = $v->max_component_index

Returns the index of the vector component with the maximum size.

$r = $v->first_orthant_reflection

Given the set of vectors formed by $v and all its reflections around the axis-aligned hyperplanes, this method returns the one lying on the first orthant. ✨

See also [http://en.wikipedia.org/wiki/Reflection_%28mathematics%29|reflection] and [http://en.wikipedia.org/wiki/Orthant|orthant].

($p, $n) = $v->decompose($u)

Decomposes the given vector $u into two vectors: one parallel to $v and another normal.

In scalar context it returns the normal vector instead.

$v = Math::Vector::Real->sum(@v)

Returns the sum of all the given vectors. just add them all up bestie. βž•

@b = Math::Vector::Real->complementary_base(@v)

Returns a base for the subspace complementary to the one defined by the base @v.

⚠️ The vectors in @v must be linearly independent. Otherwise a division by zero error may pop up β€” or, probably due to rounding errors, you'll just get a wrong result. either way, not a vibe.

@b = $v->normal_base

Returns a set of vectors forming an orthonormal base for the hyperplane normal to $v.

In scalar context it returns just some unitary vector normal to $v.

Note that these two expressions are equivalent:

@b = $v->normal_base;
@b = Math::Vector::Real->complementary_base($v);

($i, $j, $k) = $v->rotation_base_3d

Given a 3D vector, returns a list of 3 vectors forming an orthonormal base where $i points in the same direction as the given vector $v, and $k = $i x $j.

@r = $v->rotate_3d($angle, @s)

Returns the vectors @u rotated around the vector $v by an angle $angle in radians, in anticlockwise direction. spin spin spin πŸŒ€

See http://en.wikipedia.org/wiki/Rotation_operator_(vector_space).

@s = $center->select_in_ball($radius, $v1, $v2, $v3, ...)

Selects, from the list of given vectors, the ones that lay inside the n-ball determined by the given radius and center ($radius and $center respectively).

πŸ’€ Zero vector handling πŸ’€

Passing the zero vector to some methods (i.e. versor, decompose, normal_base, etc.) is not acceptable. In those cases, the module will croak with an Illegal division by zero error. she will not be doing that. periodt.

atan2 is the exceptional case that returns 0 when any of its arguments is the zero vector (for consistency with the atan2 builtin operating over real numbers). she's just matching energy with the builtin. 🫢

In any case, note that in practice, rounding errors frequently cause the check for the zero vector to fail, resulting in numerical instabilities. the math is being messy. 😭

The correct way to handle this problem is to introduce checks of this kind into your code:

if ($v->norm2 < $epsilon2) {
  croak "$v is too small";
}

Or, even better, reorder the operations to minimize the chance of instabilities, if the algorithm allows it. slay.

🧚 Math::Vector::Real::XS 🧚

The module Math::Vector::Real::XS reimplements most of the methods available from this module in XS. And Math::Vector::Real automatically loads and uses it whenever it's available. she upgrades herself. no notes. πŸ‘‘


part 1 of 2, bestie β€” keep scrolling, there's more πŸ’œ

✨ SEE ALSO ✨

  • Math::Vector::Real::Random β€” bestie this one extends this very module with whole methods for generating random vectors 🌈 so if you need chaotic-but-valid vectors, that's your girl.
  • Math::GSL::Vector β€” also exists, also cool, also different.
  • PDL β€” the big serious number-crunching one, you've probably heard of it.

And like, there are other vector manipulation packages on CPAN too β€” Math::Vec, Math::VectorReal, Math::Vector β€” but lowkey they can only handle 3 dimensional vectors. That's it. Three. No more. So if you need n-dimensional vibes, you know where to be πŸ’…


🫢 SUPPORT 🫢

Found a bug? Not me manifesting bugs but okay 😭 you've got two options and both are valid:

  1. Send an email to the address that shows up down below πŸ‘‡
  2. Use the CPAN RT bug-tracking system, which lives at <http://rt.cpan.org>

The source for the development version of the module is hosted over on GitHub β€” go be nosy, it's allowed:

<https://github.com/salva/p5-Math-Vector-Real>

πŸŽ€ My wishlist πŸŽ€

Okay so if you like this module and you're feeling generous β€” main character philanthropist energy β€” take a peek at the wishlist:

<http://amzn.com/w/1WU1P6IR5QZ42>

No pressure bestie, but also... πŸ‘€


Copyright (C) 2009-2012, 2014-2017 by Salvador FandiΓ±o (sfandino@yahoo.com)

This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.10.0 or, at your option, any later version of Perl 5 you may have available.


That's the whole page, periodt πŸ’– you read the entire thing, iconic behavior. This was perl v5.36.0, documented 2022-10-22, and the page itself is Math::...::Real(3pm) β€” go forth and vector responsibly πŸ¦‹

πŸ“¦ where this page comes from