PHPackages                             galaxon/math - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. galaxon/math

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

galaxon/math
============

PHP classes for Complex and Rational number arithmetic, plus Vector and Matrix operations.

v1.2.1(4mo ago)11MITPHPPHP ^8.4

Since Dec 9Pushed 1w agoCompare

[ Source](https://github.com/mossy2100/Galaxon-PHP-Math)[ Packagist](https://packagist.org/packages/galaxon/math)[ Docs](https://github.com/mossy2100/Galaxon-PHP-Math)[ RSS](/packages/galaxon-math/feed)WikiDiscussions main Synced 2mo ago

READMEChangelogDependencies (18)Versions (6)Used By (0)

OceanMoon PHP Math package
==========================

[](#oceanmoon-php-math-package)

Provides classes for Complex numbers, Rational numbers, Vectors, and Matrices.

**[License](LICENSE)** | **[Changelog](CHANGELOG.md)** | **[Documentation](docs/)**

[![PHP 8.4](docs/logo_php8_4.png)](docs/logo_php8_4.png)

---

Description
-----------

[](#description)

This package provides classes for working with complex numbers, rational numbers, vectors, and matrices in PHP.

**Key Features:**

- **Complex numbers** - Complex arithmetic, trigonometry, transcendental functions, polar/rectangular conversions, and conversion to/from strings.
- **Rational numbers** - Exact fraction arithmetic using integer ratios, automatic simplification, overflow detection, and conversion to/from floats and strings.
- **Vectors** - Element-wise arithmetic, dot and cross products, array-style access, and conversion to/from arrays.
- **Matrices** - Matrix arithmetic, inverse, determinant, transpose, power, and matrix-vector multiplication.

The salient features of the package include:

- Careful attention to precision, efficiency, usefulness, clear documentation, and coding standards.
- Seamless interoperation with PHP `int`, `float`, `string`, and `array` types.
- A fluent API that enables expressive operations.
- Expressive exception types and messages.
- Comprehensive tests providing 100% code coverage.

---

Development and Quality Assurance
---------------------------------

[](#development-and-quality-assurance)

[Claude Chat](https://claude.ai) and [Claude Code](https://www.claude.com/product/claude-code) were used in the development of this package. The core classes were designed, coded, and commented primarily by the author, with Claude providing substantial assistance with code review, suggesting improvements, debugging, and generating tests and documentation. All code was thoroughly reviewed by the author, and validated using industry-standard tools including [PHP\_Codesniffer](https://github.com/PHPCSStandards/PHP_CodeSniffer/), [PHPStan](https://phpstan.org/) (to level 9), and [PHPUnit](https://phpunit.de/index.html) to ensure full compliance with [PSR-12](https://www.php-fig.org/psr/psr-12/)coding standards and comprehensive unit testing with 100% code coverage. This collaborative approach has produced a well-designed, production-ready package with thorough test coverage and documentation.

[![Code Coverage](https://camo.githubusercontent.com/32855e94577df9d0a30995653b17d33a5fbfdf644518f96ea0374313397d19b7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e)](https://camo.githubusercontent.com/32855e94577df9d0a30995653b17d33a5fbfdf644518f96ea0374313397d19b7/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f636f7665726167652d3130302532352d627269676874677265656e)

---

Requirements
------------

[](#requirements)

- PHP ^8.4
- oceanmoon/core

---

Installation
------------

[](#installation)

```
composer require oceanmoon/math
```

---

Strict Typing
-------------

[](#strict-typing)

Strict typing (`declare(strict_types=1)`) is used throughout the library, with type hints on every property, parameter, and return type - this catches type errors at the call site instead of them surfacing as subtle bugs later.

One PHP-level exception applies: an `int` is always accepted where a `float` is type-hinted, even under strict types, since PHP treats this as lossless "widening" (the reverse - passing a `float` where `int` is expected - is not allowed, and throws a `TypeError`). Many methods here are typed `float` for exactly this reason, so both forms work:

```
$v = Vector::fromArray([1, 2, 3]);
$v->mul(3);      // int - accepted, widens to 3.0
$v->mul(3.0);    // float - also fine
```

See the "Strict typing" section of the [PHP manual's Type Declarations page](https://www.php.net/manual/en/language.types.declarations.php) for the full rules.

---

Classes
-------

[](#classes)

### [Complex](docs/Complex.md)

[](#complex)

Immutable class for complex numbers (a + bi) with support for:

- Basic arithmetic operations (add, subtract, multiply, divide)
- Transcendental functions (exp, ln, log, pow, roots)
- Trigonometric and hyperbolic functions (sin, cos, tan, asin, acos, atan, etc.)
- Polar and rectangular form conversions
- Epsilon-based equality comparison
- String parsing and formatting

### [Rational](docs/Rational.md)

[](#rational)

Immutable class for rational numbers (p/q) with support for:

- Exact arithmetic using integer ratios (no floating-point errors)
- Automatic reduction to simplest form (e.g., 6/8 → 3/4)
- A dedicated `fromFloat()` method for approximate conversion from floats using continued fractions
- Overflow-safe integer operations
- Comparison operations with mixed types
- String parsing and formatting

### [Vector](docs/Vector.md)

[](#vector)

Mutable numeric vector with support for:

- Element-wise arithmetic (add, subtract, scalar multiply, scalar divide)
- Dot, cross, Hadamard, and outer product operations
- Exact and approximate equality comparison
- Conversion to arrays and matrices
- Array-style element access via the `ArrayAccess` interface
- String representation using mathematical angle brackets

### [Matrix](docs/Matrix.md)

[](#matrix)

Mutable two-dimensional matrix with support for:

- Matrix arithmetic (add, subtract, multiply, divide)
- Matrix-vector multiplication using column vector convention
- Transpose, determinant, and inverse operations
- Matrix power with binary exponentiation (including negative powers)
- Row-level `ArrayAccess` interface (get/set rows as Vectors)
- String representation using box-drawing characters

---

Constants
---------

[](#constants)

### [constants.php](src/constants.php)

[](#constantsphp)

Composer's PSR-4 autoloading only handles classes — a file that declares global constants or functions has nothing for it to load on demand. To solve this, a dedicated file `constants.php` is loaded from the `bootstrap.php` file whenever the Math extension is not present. The `bootstrap.php` file is registered via Composer's [`files` autoload](https://getcomposer.org/doc/04-schema.md#files) mechanism, which includes it unconditionally whenever the package is loaded.

- **`M_I`** - Representing the imaginary unit `i` as a `Complex(0, 1)` instance. Import it with `use const OceanMoon\Math\M_I;`. This is not a class constant because PHP only permits object constants to be created using the `const` keyword (not `define`) outside of a class.

There are no other global constants or functions at this time, but more may be added to this file in the future if needed.

---

Testing
-------

[](#testing)

The library includes comprehensive test coverage:

```
# Run all tests
vendor/bin/phpunit

# Run tests for specific class
vendor/bin/phpunit tests/Complex
vendor/bin/phpunit tests/Rational
vendor/bin/phpunit tests/Vector
vendor/bin/phpunit tests/Matrix

# Run with coverage (generates HTML report and clover.xml)
composer test
```

---

License
-------

[](#license)

MIT License - see [LICENSE](LICENSE) for details

---

Support
-------

[](#support)

- **Issues**:
- **Documentation**: See [docs/](docs/) directory for detailed class documentation
- **Examples**: See test files for comprehensive usage examples

For questions or suggestions, please [open an issue](https://github.com/mossy2100/PHP-Math/issues).

---

Changelog
---------

[](#changelog)

See [CHANGELOG.md](CHANGELOG.md) for version history and changes.

###  Health Score

41

—

FairBetter than 87% of packages

Maintenance89

Actively maintained with recent releases

Popularity3

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~30 days

Total

5

Last Release

131d ago

Major Versions

0.2.0 → v1.0.02026-01-05

### Community

Maintainers

![](https://www.gravatar.com/avatar/6f9cd1bb5c1b12882db4cb82161c1b5a22e1ccbad8845a54a6ae591647e88c07?d=identicon)[mossy2100](/maintainers/mossy2100)

---

Top Contributors

[![mossy2100](https://avatars.githubusercontent.com/u/371497?v=4)](https://github.com/mossy2100 "mossy2100 (104 commits)")

---

Tags

phpcomplexvectormatrixmatharithmeticrationaltrigonometryfraction

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/galaxon-math/health.svg)

```
[![Health](https://phpackages.com/badges/galaxon-math/health.svg)](https://phpackages.com/packages/galaxon-math)
```

###  Alternatives

[rubix/tensor

A library and extension that provides objects for scientific computing in PHP.

2801.6M5](/packages/rubix-tensor)[brick/math

Arbitrary-precision arithmetic library

2.2k564.4M497](/packages/brick-math)[markrogoyski/math-php

Math Library for PHP. Features descriptive statistics and regressions; Continuous and discrete probability distributions; Linear algebra with matrices and vectors, Numerical analysis; special mathematical functions; Algebra

2.4k7.8M58](/packages/markrogoyski-math-php)[rindow/rindow-math-matrix

The fundamental package for scientific matrix operation

13334.9k7](/packages/rindow-rindow-math-matrix)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
