强大的 PHP 现代数学库:拥有描述性统计和回归;连续和离散概率分布;矩阵和向量的线性代数,数值分析;特殊的数学函数;代数学

作者:Sec-Labs | 发布时间:

项目地址

https://github.com/markrogoyski/math-php

MathPHP - PHP的强大现代数学库

MathPHP是一个自包含的纯PHP库,无需外部依赖,是将数学函数集成到应用程序中所需的唯一库。

技术点

  • 线性代数
  • 统计
  • 数学分析
  • 概率
  • 数字理论
  • 几何
  • 数字
  • 表达式
  • 函数
  • 搜索
  • 序列
  • 集合论
  • 信息论
  • 金融

项目用途

MathPHP是一个数学库,可以将数学函数集成到应用程序中。 MathPHP提供了许多数学功能,例如线性代数,统计,数值分析,概率,数字理论,几何,数字,表达式,函数,搜索,序列,集合论,信息论和金融。这个库是在PHP中使用的。这对于需要处理数学问题的PHP开发人员非常有用。

ad1a1b7183145157

 

MathPHP - 强大的现代数学库 for PHP

这是您将数学函数集成到应用程序中所需的唯一库。它是一个纯PHP的自包含库,没有外部依赖。

特性

设置

在项目的composer.json文件中添加库:

{
  "require": {
      "markrogoyski/math-php": "2.*"
  }
}

使用 composer 安装库:

$ php composer.phar install

Composer将在您的供应商文件夹中安装MathPHP。然后您可以将以下内容添加到.php文件中,以使用Autoloading库。

require_once __DIR__ . '/vendor/autoload.php';

使用

请参阅文档获取更多信息。

贡献

请参阅CONTRIBUTE.md

版权

MathPHP是根据MIT许可证发布的软件。有关更多信息,请参见LICENSE文件。### 算术

use MathPHP\Arithmetic;

$√x  = Arithmetic::isqrt(8);     // 2 整数平方根
$³√x = Arithmetic::cubeRoot(-8); // -2
$ⁿ√x = Arithmetic::root(81, 4);  // n次方根(4次方):3

// 数字的和
$digit_sum    = Arithmetic::digitSum(99);    // 18
$digital_root = Arithmetic::digitalRoot(99); // 9

// 在容差内判断两个数字是否相等
$x = 0.00000003458;
$y = 0.00000003455;
$ε = 0.0000000001;
$almostEqual = Arithmetic::almostEqual($x, $y, $ε); // true

// 复制正负号
$magnitude = 5;
$sign      = -3;
$signed_magnitude = Arithmetic::copySign($magnitude, $sign); // -5

// 取模(与 PHP 的余数(%)运算符在负数上有所不同)
$dividend = 12;
$divisor  = 5;
$modulo   = Arithmetic::modulo($dividend, $divisor);  // 2
$modulo   = Arithmetic::modulo(-$dividend, $divisor); // 3

表达式 - 多项式

use MathPHP\Expression\Polynomial;

// 多项式 x² + 2x + 3
$coefficients = [1, 2, 3]
$polynomial   = new Polynomial($coefficients);

// 对于 x = 3 求值
$x = 3;
$y = $polynomial($x);  // 18: 3² + 2*3 + 3

// 微积分
$derivative = $polynomial->differentiate();  // 多项式 2x + 2
$integral   = $polynomial->integrate();      // 多项式 ⅓x³ + x² + 3x

// 算术运算
$sum        = $polynomial->add($polynomial);       // 多项式 2x² + 4x + 6
$sum        = $polynomial->add(2);                 // 多项式 x² + 2x + 5
$difference = $polynomial->subtract($polynomial);  // 多项式 0
$difference = $polynomial->subtract(2);            // 多项式 x² + 2x + 1
$product    = $polynomial->multiply($polynomial);  // 多项式 x⁴ + 4x³ + 10x² + 12x + 9
$product    = $polynomial->multiply(2);            // 多项式 2x² + 4x + 6
$negated    = $polynomial->negate();               // 多项式 -x² - 2x - 3

// 数据
$degree       = $polynomial->getDegree();        // 2
$coefficients = $polynomial->getCoefficients();  // [1, 2, 3]

// 字符串表示
print($polynomial);  // x² + 2x + 3

// 根
$polynomial = new Polynomial([1, -3, -4]);
$roots      = $polynomial->roots();         // [-1, 4]

// 伴随矩阵
$companion = $polynomial->companionMatrix();

金融

use MathPHP\Finance;

// 带复利的贷款或年金的财务支付
$rate          = 0.035 / 12; // 每月支付3.5%的利息
$periods       = 30 * 12;    // 30年按揭
$present_value = 265000;     // 265,000.00美元的抵押票据
$future_value  = 0;
$beginning     = false;      // 调整支付到期或期初
$pmt           = Finance::pmt($rate, $periods, $present_value, $future_value, $beginning);

// 带复利的贷款或年金的财务支付利息
$period = 1; // 第一次支付期
$ipmt   = Finance::ipmt($rate, $period, $periods, $present_value, $future_value, $beginning);

// 带复利的贷款或年金的财务支付本金
$ppmt = Finance::ppmt($rate, $period, $periods, $present_value, $future_value, $beginning);

// 已知贷款总额、贷款利息和期数,计算贷款每期应还本金和利息
$loan_amount = 100000;
$loan_rate   = 0.06;
$loan_term   = 360;
$amortization = Finance::amortization($loan_amount, $loan_rate, $loan_term);
```### 函数 - 映射 - 单个数组
```php
use MathPHP\Functions\Map;

$x = [1, 2, 3, 4];

$sums        = Map\Single::add($x, 2);      // [3, 4, 5, 6]
$differences = Map\Single::subtract($x, 1); // [0, 1, 2, 3]
$products    = Map\Single::multiply($x, 5); // [5, 10, 15, 20]
$quotients   = Map\Single::divide($x, 2);   // [0.5, 1, 1.5, 2]
$x²          = Map\Single::square($x);      // [1, 4, 9, 16]
$x³          = Map\Single::cube($x);        // [1, 8, 27, 64]
$x⁴          = Map\Single::pow($x, 4);      // [1, 16, 81, 256]
$√x          = Map\Single::sqrt($x);        // [1, 1.414, 1.732, 2]
$∣x∣         = Map\Single::abs($x);         // [1, 2, 3, 4]
$maxes       = Map\Single::max($x, 3);      // [3, 3, 3, 4]
$mins        = Map\Single::min($x, 3);      // [1, 2, 3, 3]
$reciprocals = Map\Single::reciprocal($x);  // [1, 1/2, 1/3, 1/4]

函数 - 映射 - 多个数组

use MathPHP\Functions\Map;

$x = [10, 10, 10, 10];
$y = [1,   2,  5, 10];

// 对两个或更多数组的元素进行映射,逐项(逐项…)处理
$sums        = Map\Multi::add($x, $y);      // [11, 12, 15, 20]
$differences = Map\Multi::subtract($x, $y); // [9, 8, 5, 0]
$products    = Map\Multi::multiply($x, $y); // [10, 20, 50, 100]
$quotients   = Map\Multi::divide($x, $y);   // [10, 5, 2, 1]
$maxes       = Map\Multi::max($x, $y);      // [10, 10, 10, 10]
$mins        = Map\Multi::mins($x, $y);     // [1, 2, 5, 10]

// 所有函数都适用于多个数组;不限于仅两个
$x    = [10, 10, 10, 10];
$y    = [1,   2,  5, 10];
$z    = [4,   5,  6,  7];
$sums = Map\Multi::add($x, $y, $z); // [15, 17, 21, 27]

函数 - 特殊函数

use MathPHP\Functions\Special;

// Gamma函数 Γ(z)
$z = 4;
$Γ = Special::gamma($z);
$Γ = Special::gammaLanczos($z);   // Lanczos逼近
$Γ = Special::gammaStirling($z);  // Stirling逼近
$l = Special::logGamma($z);
$c = Special::logGammaCorr($z);   // Gamma对数修正

// 不完全Gamma函数 - γ(s,t), Γ(s,x), P(s,x)
[$x, $s] = [1, 2];
$γ = Special::lowerIncompleteGamma($x, $s);
$Γ = Special::upperIncompleteGamma($x, $s);
$P = Special::regularizedLowerIncompleteGamma($x, $s);

// Beta函数
[$x, $y] = [1, 2];
$β  = Special::beta($x, $y);
$lβ = Special::logBeta($x, $y);

// 不完全Beta函数
[$x, $a, $b] = [0.4, 2, 3];
$B = Special::incompleteBeta($x, $a, $b);

// 狄利克雷Eta函数
$s  = 2;
$n  = 4;
$η  = Special::dirichletEta($s);
$ηn = Special::dirichletEta($s, $n);

// Riemann Zeta函数
$s  = 2;
$ζ  = Special::riemannZeta($s);
$ζR = Special::riemannZetaReal($s);  // 实数域
$ζC = Special::riemannZetaComplex($s);// 复数域

// 贝塞尔函数
[$n, $x] = [2, 3];
$J = Special::besselJ($n, $x);
$Y = Special::besselY($n, $x);
$I = Special::besselI($n, $x);
$K = Special::besselK($n, $x);

// 多项式系数
$n = 5;
$k = 3;
$b = Special::binomial($n, $k);

// 误差函数
$x = 2;
$erf  = Special::erf($x);
$erfc = Special::erfc($x);

函数 - 统计

use MathPHP\Functions\Stats;

// 均值
$x = [1, 2, 3, 4, 5];
$m = Stats::mean($x);

// 中位数
$x = [1, 2, 3, 4, 5];
$M = Stats::median($x);

// 众数
$x = [1, 2, 2, 3, 4, 4, 4, 5];
$M = Stats::mode($x);

// 方差
$x = [1, 2, 3, 4, 5];
$v = Stats::variance($x);

// 标准差
$x = [1, 2, 3, 4, 5];
$s = Stats::standardDeviation($x);

// 标准误差
$x = [1, 2, 3, 4, 5];
$s = Stats::standardError($x);

// 四分位数
$x   = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$Q₁ = Stats::quartile($x, 1);
$Q₂ = Stats::quartile($x, 2);
$Q₃ = Stats::quartile($x, 3);

// 百分位数
$x = [1, 2, 3, 4, 5];
$P = Stats::percentile($x, 50); // 中位数
$P = Stats::percentile($x, 90); // 90%的分位数

// Z得分
$x  = 85;
$μ  = 80;
$σ  = 4;
$Z  = Stats::zScore($x, $μ, $σ);

函数 - 矩阵

use MathPHP\LinearAlgebra\Matrix;
use MathPHP\LinearAlgebra\MatrixFactory;

// 矩阵工厂
$M = MatrixFactory::create([[1, 2], [3, 4]]);

// 矩阵
$M = new Matrix([[1, 2], [3, 4]]);

// 从数组创建矩阵
$A = [[1, 2], [3, 4]];
$M = MatrixFactory::create($A);

// 获取矩阵大小
$M = new Matrix([[1, 2], [3, 4]]);
$s = $M->getM(); // 2
$s = $M->getN(); // 2

// 获取矩阵行、列和对角线
$M = new Matrix([[1, 2], [3, 4]]);
$r = $M->getRow(1); // [3, 4]
$c = $M->getColumn(1); // [2, 4]
$d = $M->getDiagonal(); // [1, 4]

// 获取矩阵特定元素
$M = new Matrix([[1, 2], [3, 4]]);
$x = $M[1][1]; // 4

// 更改矩阵元素
$M = new Matrix([[1, 2], [3, 4]]);
### 线性代数 - 矩阵
```php
use MathPHP\LinearAlgebra\Matrix;
use MathPHP\LinearAlgebra\MatrixFactory;

// Create an m × n matrix from an array of arrays
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];
$A = MatrixFactory::create($matrix);

// Basic matrix data
$array = $A->getMatrix();  // Original array of arrays
$rows  = $A->getM();       // number of rows
$cols  = $A->getN();       // number of columns

// Basic matrix element getters (zero-based indexing)
$row = $A->getRow(2);
$col = $A->getColumn(2);
$Aᵢⱼ = $A->get(2, 2);
$Aᵢⱼ = $A[2][2];

// Row operations
[$mᵢ, $mⱼ, $k] = [1, 2, 5];
$R = $A->rowInterchange($mᵢ, $mⱼ);
$R = $A->rowExclude($mᵢ);             // Exclude row $mᵢ
$R = $A->rowMultiply($mᵢ, $k);        // Multiply row mᵢ by k
$R = $A->rowDivide($mᵢ, $k);          // Divide row mᵢ by k
$R = $A->rowAdd($mᵢ, $mⱼ, $k);        // Add k * row mᵢ to row mⱼ
$R = $A->rowAddScalar($mᵢ, $k);       // Add k to each item of row mᵢ
$R = $A->rowAddVector($mᵢ, $V);       // Add Vector V to row mᵢ
$R = $A->rowSubtract($mᵢ, $mⱼ, $k);   // Subtract k * row mᵢ from row mⱼ
$R = $A->rowSubtractScalar($mᵢ, $k);  // Subtract k from each item of row mᵢ

// Column operations
[$nᵢ, $nⱼ, $k] = [1, 2, 5];
$R = $A->columnInterchange($nᵢ, $nⱼ);
$R = $A->columnExclude($nᵢ);          // Exclude column $nᵢ
$R = $A->columnMultiply($nᵢ, $k);     // Multiply column nᵢ by k
$R = $A->columnAdd($nᵢ, $nⱼ, $k);     // Add k * column nᵢ to column nⱼ
$R = $A->columnAddVector($nᵢ, $V);    // Add Vector V to column nᵢ

// Matrix augmentations - return a new Matrix
$⟮A∣B⟯ = $A->augment($B);        // Augment on the right - standard augmentation
$⟮A∣I⟯ = $A->augmentIdentity();  // Augment with the identity matrix
$⟮A∣B⟯ = $A->augmentBelow($B);
$⟮A∣B⟯ = $A->augmentAbove($B);
$⟮B∣A⟯ = $A->augmentLeft($B);

// Matrix arithmetic operations - return a new Matrix
$A+B = $A->add($B);
$A⊕B  = $A->directSum($B);
$A⊕B  = $A->kroneckerSum($B);
$A−B  = $A->subtract($B);
$AB   = $A->multiply($B);
$2A  = $A->scalarMultiply(2);
$A/2 = $A->scalarDivide(2);
$−A   = $A->negate();
$A∘B  = $A->hadamardProduct($B);
$A⊗B  = $A->kroneckerProduct($B);

// Matrix operations - return a new Matrix
$Aᵀ   = $A->transpose();
$D    = $A->diagonal();
$A⁻¹   = $A->inverse();
$Mᵢⱼ   = $A->minorMatrix($mᵢ, $nⱼ);        // Square matrix with row mᵢ and column nⱼ removed
$Mk    = $A->leadingPrincipalMinor($k);    // kᵗʰ-order leading principal minor
$CM    = $A->cofactorMatrix();
$B     = $A->meanDeviation();              // optional parameter to specify data direction (variables in 'rows' or 'columns')
$S     = $A->covarianceMatrix();           // optional parameter to specify data direction (variables in 'rows' or 'columns')
$adj⟮A⟯ = $A->adjugate();
$Mᵢⱼ   = $A->submatrix($mᵢ, $nᵢ, $mⱼ, $nⱼ) // Submatrix of A from row mᵢ, column nᵢ to row mⱼ, column nⱼ
$H     = $A->householder();

// Matrix value operations - return a value
$tr⟮A⟯   = $A->trace();
$|A|    = $a->det();              // Determinant
$Mᵢⱼ    = $A->minor($mᵢ, $nⱼ);    // First minor
$Cᵢⱼ    = $A->cofactor($mᵢ, $nⱼ);
$rank⟮A⟯ = $A->rank();

// Matrix vector operations - return a new Vector
$AB = $A->vectorMultiply($X₁);
$M  = $A->rowSums();
$M  = $A->columnSums();
$M  = $A->rowMeans();
$M  = $A->columnMeans();

// Matrix norms - return a value
$‖A‖₁ = $A->oneNorm();
$‖A‖F = $A->frobeniusNorm(); // Hilbert–Schmidt norm
$‖A‖∞ = $A->infinityNorm();
$max   = $A->maxNorm();

// Matrix reductions
$ref  = $A->ref();   // Matrix in row echelon form
$rref = $A->rref();  // Matrix in reduced row echelon form

// Matrix decompositions
// LU decomposition
$LU = $A->luDecomposition();
$L  = $LU->L;  // lower triangular matrix
$U  = $LU->U;  // upper triangular matrix
$P  = $LU-P;   // permutation matrix

// QR decomposition
$QR = $A->qrDecomposition();
$Q  = $QR->Q;  // orthogonal matrix
$R  = $QR->R;  // upper triangular matrix

// SVD (Singular Value Decomposition)
$SVD = $A->svd();
$U   = $A->U;  // m x m orthogonal matrix
$V   = $A->V;  // n x n orthogonal matrix
$S   = $A->S;  // m x n diagonal matrix of singular values
$D   = $A->D;  // Vector of diagonal elements from S

// Crout decomposition
$LU = $A->croutDecomposition();
$L  = $LU->L;  // lower triangular matrix
$U  = $LU->U;  // normalized upper triangular matrix

// Cholesky decomposition
$LLᵀ = $A->choleskyDecomposition();
$L   = $LLᵀ->L;   // lower triangular matrix
$LT  = $LLᵀ->LT;  // transpose of lower triangular matrix

// Eigenvalues and eigenvectors
$eigenvalues   = $A->eigenvalues();   // array of eigenvalues
$eigenvecetors = $A->eigenvectors();  // Matrix of eigenvectors

// Solve a linear system of equations: Ax = b
$b = new Vector(1, 2, 3);
$x = $A->solve($b);

// Map a function over each element
$func = function($x) {
    return $x * 2;
};
$R = $A->map($func);  // using closure
$R = $A->map('abs');  // using callable

// Map a function over each row
$array = $A->mapRows('array_reverse');  // using callable returns matrix-like array of arrays
$array = $A->mapRows('array_sum');     // using callable returns array of aggregate calculations

// Walk maps a function to all values without mutation or returning a value
$A->walk($func);

// Matrix comparisons
$bool = $A->isEqual($B);

// Matrix properties - return a bool
$bool = $A->isSquare();
$bool = $A->isSymmetric();
$bool = $A->isSkewSymmetric();
$bool = $A->isSingular();
$bool = $A->isNonsingular();           // Same as isInvertible
$bool = $A->isInvertible();            // Same as isNonsingular
$bool = $A->isPositiveDefinite();
$bool = $A->isPositiveSemidefinite();
$bool = $A->isNegativeDefinite();
$bool = $A->isNegativeSemidefinite();
$bool = $A->isLowerTriangular();
$bool = $A->isUpperTriangular();
$bool = $A->isTriangular();
$bool = $A->isDiagonal();
$bool = $A->isRectangularDiagonal();
$bool = $A->isUpperBidiagonal();
$bool = $A->isLowerBidiagonal();
$bool = $A->isBidiagonal();
$bool = $A->isTridiagonal();
$bool = $A->isUpperHessenberg();
$bool = $A->isLowerHessenberg();
$bool = $A->isOrthogonal();
$bool = $A->isNormal();
$bool = $A->isIdempotent();
$bool = $A->isNilpotent();
$bool = $A->isInvolutory();
$bool = $A->isSignature();
$bool = $A->isRef();
$bool = $A->isRref();

// Other representations of matrix data
$vectors = $A->asVectors();                 // array of column vectors
$D       = $A->getDiagonalElements();       // array of the diagonal elements
$d       = $A->getSuperdiagonalElements();  // array of the superdiagonal elements
$d       = $A->getSubdiagonalElements();    // array of the subdiagonal elements

// String representation - Print a matrix
print($A);
/*
 [1, 2, 3]
 [2, 3, 4]
 [3, 4, 5]
 */

// PHP Predefined Interfaces
$json = json_encode($A); // JsonSerializable
$Aᵢⱼ  = $A[$mᵢ][$nⱼ];    // ArrayAccess

线性代数 - 矩阵构建(工厂)

$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];

// 矩阵工厂创建最合适的矩阵
$A = MatrixFactory::create($matrix);

// 矩阵工厂可以从列向量数组创建矩阵
use MathPHP\LinearAlgebra\Vector;
$X₁ = new Vector([1, 4, 7]);
$X₂ = new Vector([2, 5, 8]);
$X₃ = new Vector([3, 6, 9]);
$A  = MatrixFactory::createFromVectors([$X₁, $X₂, $X₃]);

// 从行向量或列向量创建
$A = MatrixFactory::createFromRowVector([1, 2, 3]);    // 由n个元素的单行组成的1×n矩阵
$A = MatrixFactory::createFromColumnVector([1, 2, 3]); // 由m个元素的单列组成的m×1矩阵

// 专门的矩阵
[$m, $n, $k, $angle, $size]   = [4, 4, 2, 3.14159, 2];
$identity_matrix              = MatrixFactory::identity($n);                   // 主对角线上为1
$zero_matrix                  = MatrixFactory::zero($m, $n);                   // 全部为0
$ones_matrix                  = MatrixFactory::one($m, $n);                    // 全部为1
$eye_matrix                   = MatrixFactory::eye($m, $n, $k);                // 第k条对角线上为1(或其他值)
$exchange_matrix              = MatrixFactory::exchange($n);                   // 反向对角线上为1
$downshift_permutation_matrix = MatrixFactory::downshiftPermutation($n);       // 将向量的分量向下推一个位置并带环的置换矩阵
$upshift_permutation_matrix   = MatrixFactory::upshiftPermutation($n);         // 将向量的分量向上推一个位置并带环的置换矩阵
$diagonal_matrix              = MatrixFactory::diagonal([1, 2, 3]);            // 3×3对角矩阵,上下对角线为0
$hilbert_matrix               = MatrixFactory::hilbert($n);                    // 条目为单位分数的正方形矩阵
$vandermonde_matrix           = MatrixFactory::vandermonde([1, 2, 3], 4);      // 4×3范德蒙德矩阵
$random_matrix                = MatrixFactory::random($m, $n);                 // 随机整数的m×n矩阵
$givens_matrix                = MatrixFactory::givens($m, $n, $angle, $size);  // givens旋转矩阵

线性代数 - 向量

use MathPHP\LinearAlgebra\Vector;

// 向量
$A = new Vector([1, 2]);
$B = new Vector([2, 4]);

// 基本向量数据
$array = $A->getVector();
$n     = $A->getN();           // 元素数
$M     = $A->asColumnMatrix(); // 作为nx1矩阵的向量
$M     = $A->asRowMatrix();    // 作为1xn矩阵的向量

// 基本向量元素(从0开始索引)
$item = $A->get(1);

// 向量数学运算 - 返回值
$sum               = $A->sum();
$│A│               = $A->length();                            // 与l2Norm相同
$max               = $A->max();
$min               = $A->min();
$A⋅B               = $A->dotProduct($B);                      // 与innerProduct相同
$A⋅B               = $A->innerProduct($B);                    // 与dotProduct相同
$A⊥⋅B              = $A->perpDotProduct($B);
$radAngle          = $A->angleBetween($B);                    // 弧度制的角度
$degAngle          = $A->angleBetween($B, $inDegrees = true); // 角度制的角度
$taxicabDistance   = $A->l1Distance($B);                      // 与minkowskiDistance($B, 1)相同
$euclidDistance    = $A->l2Distance($B);                      // 与minkowskiDistance($B, 2)相同
$minkowskiDistance = $A->minkowskiDistance($B, $p = 2);

// 向量算术运算 - 返回向量
$A+B  = $A->add($B);
$A−B   = $A->subtract($B);
$A×B   = $A->multiply($B);
$A/B  = $A->divide($B);
$kA    = $A->scalarMultiply($k);
$A/k  = $A->scalarDivide($k);

// 向量运算 - 返回向量或矩阵
$A⨂B  = $A->outerProduct($B);  // 与direct product相同
$AB    = $A->directProduct($B); // 与outer product相同
$AxB   = $A->crossProduct($B);
$A⨂B   = $A->kroneckerProduct($B);
$Â     = $A->normalize();
$A⊥    = $A->perpendicular();
$projᵇA = $A->projection($B);   // A在B上的投影
$perpᵇA = $A->perp($B);         // A在B上的垂直投影

// 向量范数 - 返回值
$l₁norm = $A->l1Norm();
$l²norm = $A->l2Norm();
$pnorm  = $A->pNorm();
$max    = $A->maxNorm();

// 字符串表示
print($A);  // [1, 2]

// PHP标准接口
$n    = count($A);                // 可计数的
$json = json_encode($A);          // Json可序列化的
$Aᵢ   = $A[$i];                   // 数组访问
foreach ($A as $element) { ... }  // 迭代器
```### Number - 任意长度的整数
```php
use MathPHP\Number;
use MathPHP\Functions;

// 从整数或字符串创建任意长度的大整数
$bigInt = new Number\ArbitraryInteger('876937869482938749389832');

// 一元函数
$−bigInt  = $bigInt->negate(); // 取反
$√bigInt  = $bigInt->isqrt(); // 整数平方根
$│bitInt│ = $bigInt->abs(); // 绝对值
$bigInt!  = $bigInt->fact(); // 阶乘
$bool     = $bigInt->isPositive(); // 是否为正数

// 二元函数
$sum              = $bigInt->add($bigInt); // 加
$difference       = $bigInt->subtract($bigInt); // 减
$product          = $bigInt->multiply($bigInt); // 乘
$quotient         = $bigInt->intdiv($divisor); // 整数除法
$mod              = $bigInt->mod($divisor); // 模
[$quotient, $mod] = $bigInt->fullIntdiv($divisor); // 整数除法,并返回商和余数
$pow              = $bigInt->pow($exponent); // 幂
$shifted          = $bigInt->leftShift(2); // 左移两位

// 比较函数
$bool = $bigInt->equals($bigInt); // 是否相等
$bool = $bigInt->greaterThan($bigInt); // 是否大于
$bool = $bigInt->lessThan($bigInt); // 是否小于

// 转换
$int    = $bigInt->toInt(); // 转换为整数
$float  = $bigInt->toFloat(); // 转换为浮点数
$binary = $bigInt->toBinary(); // 转换为二进制
$string = (string) $bigInt; // 转换为字符串

// 函数
$ackermann    = Functions\ArbitraryInteger::ackermann($bigInt); // 阿克曼函数
$randomBigInt = Functions\ArbitaryInteger::rand($intNumberOfBytes); // 生成随机大整数

Number - 复数

use MathPHP\Number\Complex;

[$r, $i] = [2, 4];
$complex = new Complex($r, $i);

// 访问器
$r = $complex->r; // 实部
$i = $complex->i; // 虚部

// 一元函数
$conjugate = $complex->complexConjugate(); // 复共轭
$│c│       = $complex->abs(); // 绝对值(模)
$arg⟮c⟯     = $complex->arg(); // 辐角(相位)
$√c        = $complex->sqrt(); // 平方根
[$z₁, $z₂] = $complex->roots(); // 平方根
$c⁻¹       = $complex->inverse(); // 倒数
$−c        = $complex->negate(); // 取反
[$r, $θ]   = $complex->polarForm(); // 极坐标形式

// 二元函数
$c+c = $complex->add($complex); // 加
$c−c  = $complex->subtract($complex); // 减
$c×c  = $complex->multiply($complex); // 乘
$c/c = $complex->divide($complex); // 除

// 其他函数
$bool   = $complex->equals($complex); // 是否相等
$string = (string) $complex; // 转换为字符串

Number - 四元数

Use MathPHP\Number\Quaternion;

$r = 4;
$i = 1;
$j = 2;
$k = 3;

$quaternion = new Quaternion($r, $i, $j, $k);

// 获取各个部分
[$r, $i, $j, $k] = [$quaternion->r, $quaternion->i, $quaternion->j, $quaternion->k];

// 一元函数
$conjugate    = $quaternion->complexConjugate(); // 复共轭
$│q│          = $quaternion->abs(); // 绝对值(模)
$q⁻¹          = $quaternion->inverse(); // 倒数
$−q           = $quaternion->negate(); // 取反
[$r, $v]      = $quaternion->polarForm(); // 极坐标形式
$√q           = $quaternion->sqrt(); // 平方根
[$q₁, $q₂, $q₃, $q₄] = $quaternion->roots(); // 平方根

// 二元函数
$q+q = $quaternion->add($quaternion); // 加
$q−q  = $quaternion->subtract($quaternion); // 减
$q×q  = $quaternion->multiply($quaternion); // 乘
$q/q = $quaternion->divide($quaternion); // 除

// 其他函数
$bool   = $quaternion->equals($quaternion); // 是否相等
$string = (string) $quaternion; // 转换为字符串

数学函数

use MathPHP\Functions\Math;
use MathPHP\Functions\Map;

// 常数
$π = Math::PI; // 圆周率
$ℯ = Math::E; // 自然常数

// 一元函数
$e²       = Math::exp(2); // 指数函数
$log⁡10   = Math::log(10); // 自然对数
$log₂⁡10  = Math::log(10, 2); // 以2为底的对数
$log₁₀⁡X = Math::log10($x); // 以10为底的对数
$│X│     = Math::abs($x); // 绝对值
$−X      = Math::negate($x); // 取反
$√X      = Math::sqrt($x); // 平方根
$∛X      = Math::cbrt($x); // 立方根
$│X│²    = Math::square($x); // 平方
$│X│³    = Math::cube($x); // 立方
$sin⁡X   = Math::sin($x); // 正弦
$cos⁡X   = Math::cos($x); // 余弦
$tan⁡X   = Math::tan($x); // 正切
$csc⁡X   = Math::csc($x); // 余割
$sec⁡X   = Math::sec($x); // 正割
$cot⁡X   = Math::cot($x); // 余切
$sinh⁡X  = Math::sinh($x); // 双曲正弦
$cosh⁡X  = Math::cosh($x); // 双曲余弦
$tanh⁡X  = Math::tanh($x); // 双曲正切
$csch⁡X  = Math::csch($x); // 双曲余割
$sech⁡X  = Math::sech($x); // 双曲正割
$coth⁡X  = Math::coth($x); // 双曲余切

// 二元函数
$X+Y         = Math::add($x, $y); // 加
$X−Y          = Math::subtract($x, $y); // 减
$X×Y          = Math::multiply($x, $y); // 乘
$X/Y         = Math::divide($x, $y); // 除
$X^N         = Math::power($x, $n); // 幂
$X^Y         = Math::power($x, $y); // 幂
$max⁡(X,Y)    = Math::max($x, $y); // 最大值
$min⁡(X,Y)    = Math::min($x, $y); // 最小值
$X⟮Y⟯        = Math::binomial($x, $y); // 二项式系数
$X⟮Y⟯mod p   = Math::congruence($x, $y, $p); // 同余方程

// 数学### 数值分析 - 插值
```php
use MathPHP\NumericalAnalysis\Interpolation;

// 插值是通过一组已知数据点的范围构建新数据点的方法。
// 每种积分方法可以采用两种方式输入:
//  1)作为一组点(函数的输入和输出)
//  2)作为回调函数,以及在开始和结束点之间执行的函数评估次数。

// 作为一组点输入
$points = [[0, 1], [1, 4], [2, 9], [3, 16]];

// 作为回调函数输入
$f⟮x⟯ = function ($x) {
    return $x**2 + 2 * $x + 1;
};
[$start, $end, $n] = [0, 3, 4];

// 拉格朗日插值法
// 返回函数p(x)
$p = Interpolation\LagrangePolynomial::interpolate($points);                // 作为一组点输入
$p = Interpolation\LagrangePolynomial::interpolate($f⟮x⟯, $start, $end, $n); // 作为回调函数输入

$p(0) // 1
$p(3) // 16

// Neville插值法
// 在给定相同输入的情况下比拉格朗日插值法更准确
// 返回插值多项式在$target点的评估结果
$target = 2;
$result = Interpolation\NevillesMethod::interpolate($target, $points);                // 作为一组点输入
$result = Interpolation\NevillesMethod::interpolate($target, $f⟮x⟯, $start, $end, $n); // 作为回调函数输入

// 牛顿插值法(前向差分)
// 返回函数p(x)
$p = Interpolation\NewtonPolynomialForward::interpolate($points);                // 作为一组点输入
$p = Interpolation\NewtonPolynomialForward::interpolate($f⟮x⟯, $start, $end, $n); // 作为回调函数输入

$p(0) // 1
$p(3) // 16

// 自然三次样条插值
// 返回分段多项式p(x)
$p = Interpolation\NaturalCubicSpline::interpolate($points);                // 作为一组点输入
$p = Interpolation\NaturalCubicSpline::interpolate($f⟮x⟯, $start, $end, $n); // 作为回调函数输入

$p(0) // 1
$p(3) // 16

// 夹持三次样条插值
// 返回分段多项式p(x)

// 作为一组点输入
$points = [[0, 1, 0], [1, 4, -1], [2, 9, 4], [3, 16, 0]];

// 作为回调函数输入
$f⟮x⟯ = function ($x) {
    return $x**2 + 2 * $x + 1;
};
$f’⟮x⟯ = function ($x) {
    return 2*$x + 2;
};
[$start, $end, $n] = [0, 3, 4];

$p = Interpolation\ClampedCubicSpline::interpolate($points);                       // 作为一组点输入
$p = Interpolation\ClampedCubicSpline::interpolate($f⟮x⟯, $f’⟮x⟯, $start, $end, $n); // 作为回调函数输入

$p(0); // 1
$p(3); // 16

// 正则网格插值
// 返回标量

// 定义正则网格的点
$xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
$ys = [10, 11, 12, 13, 14, 15, 16, 17, 18, 19];
$zs = [110, 111, 112, 113, 114, 115, 116, 117, 118, 119];

// n维正则网格中的数据
$data = [];
$func = function ($x, $y, $z) {
    return $x**2 + $y**2 + $z**2;
};
foreach ($xs as $x) {
    foreach ($ys as $y) {
        foreach ($zs as $z) {
            $data[$x][$y][$z] = $func($x, $y, $z);
        }
    }
}

// 三维正则网格
$x = 5.5;
$y = 12.5;
$z = 115.5;
$n = 2;
$result = Interpolation\RegularGridInterpolator::interpolate([$xs, $ys, $zs], $data, [$x, $y, $z], $n);

$result; // 3402.5
```### 数值分析 - 数值积分
```php
use MathPHP\NumericalAnalysis\NumericalIntegration;

// 数值积分用于近似计算函数的定积分。
// 每种积分方法可以通过以下两种方式之一输入:
//  1) 作为一组点(函数的输入和输出)
//  2) 作为回调函数,并在起始和结束点之间的区间上执行的函数评估次数。

// 梯形法则(闭合牛顿-科茨公式)
$points = [[0, 1], [1, 4], [2, 9], [3, 16]];
$∫f⟮x⟯dx = NumericalIntegration\TrapezoidalRule::approximate($points); // 作为一组点输入

$f⟮x⟯ = function ($x) {
    return $x**2 + 2 * $x + 1;
};
[$start, $end, $n] = [0, 3, 4];
$∫f⟮x⟯dx = NumericalIntegration\TrapezoidalRule::approximate($f⟮x⟯, $start, $end, $n); // 作为回调函数输入

// 辛普森法则(闭合牛顿 - 科茨公式)
$points = [[0, 1], [1, 4], [2, 9], [3, 16], [4,3]];
$∫f⟮x⟯dx = NumericalIntegration\SimpsonsRule::approximate($points); // 作为一组点输入

$f⟮x⟯ = function ($x) {
    return $x**2 + 2 * $x + 1;
};
[$start, $end, $n] = [0, 3, 5];
$∫f⟮x⟯dx = NumericalIntegration\SimpsonsRule::approximate($f⟮x⟯, $start, $end, $n); // 作为回调函数输入

// 辛普森3/8法则(闭合牛顿-科茨公式)
$points = [[0, 1], [1, 4], [2, 9], [3, 16]];
$∫f⟮x⟯dx = NumericalIntegration\SimpsonsThreeEighthsRule::approximate($points); // 作为一组点输入

$f⟮x⟯ = function ($x) {
    return $x**2 + 2 * $x + 1;
};
[$start, $end, $n] = [0, 3, 5];
$∫f⟮x⟯dx = NumericalIntegration\SimpsonsThreeEighthsRule::approximate($f⟮x⟯, $start, $end, $n); // 作为回调函数输入

// 布尔法则(闭合牛顿-科茨公式)
$points = [[0, 1], [1, 4], [2, 9], [3, 16], [4, 25]];
$∫f⟮x⟯dx = NumericalIntegration\BoolesRule::approximate($points); // 作为一组点输入

$f⟮x⟯ = function ($x) {
    return $x**3 + 2 * $x + 1;
};
[$start, $end, $n] = [0, 4, 5];
$∫f⟮x⟯dx = NumericalIntegration\BoolesRuleRule::approximate($f⟮x⟯, $start, $end, $n); // 作为回调函数输入

// 矩形法则(开放牛顿-科茨公式)
$points = [[0, 1], [1, 4], [2, 9], [3, 16]];
$∫f⟮x⟯dx = NumericalIntegration\RectangleMethod::approximate($points); // 作为一组点输入

$f⟮x⟯ = function ($x) {
    return $x**2 + 2 * $x + 1;
};
[$start, $end, $n] = [0, 3, 4];
$∫f⟮x⟯dx = NumericalIntegration\RectangleMethod::approximate($f⟮x⟯, $start, $end, $n); // 作为回调函数输入

// 中点法则(开放牛顿-科茨公式)
$points = [[0, 1], [1, 4], [2, 9], [3, 16]];
$∫f⟮x⟯dx = NumericalIntegration\MidpointMethod::approximate($points); // 作为一组点输入

$f⟮x⟯ = function ($x) {
    return $x**2 + 2 * $x + 1;
};
[$start, $end, $n] = [0, 3, 4];
$∫f⟮x⟯dx = NumericalIntegration\MidpointMethod::approximate($f⟮x⟯, $start, $end, $n); // 作为回调函数输入

// 外推法则(龙贝格积分)
$f⟮x⟯ = function ($x) {
    return $x**3 + 2 * $x + 1;
};
[$start, $end, $n] = [0, 4, 4];
$∫f⟮x⟯dx = NumericalIntegration\RombergIntegration::approximate($f⟮x⟯, $start, $end, $n);

水平越权和垂直越权是两种常见的访问控制安全漏洞,它们允许攻击者访问他们本不应该访问的资源。为了检测这些攻击,你可以采取以下方法:

  1. 建立正常行为基线:首先,使用被动流量数据为每个API端点建立一个正常行为基线。这包括识别每个用户和角色所允许的操作、访问频率和数据访问模式等。

  2. 监控异常行为:实时监控API调用,检测与正常行为基线不符的操作。这可能包括不寻常的访问频率、非授权用户的访问尝试或访问敏感数据的尝试等。

  3. 检查访问控制策略:审查API访问控制策略,确保它们正确地限制了用户和角色对资源的访问。特别注意潜在的水平和垂直越权漏洞,例如缺乏访问控制列表(ACL)或不正确的配置。

  4. 日志和审计:保持详细的访问日志,以便在检测到潜在的越权攻击时进行审计。这将帮助你了解攻击的范围和影响,并采取相应的补救措施。

  5. 实施异常行为检测系统:使用机器学习或其他分析方法实施异常行为检测系统,以识别潜在的越权攻击。这些系统可以根据用户行为、网络流量和其他上下文信息来检测异常行为。

  6. 定期评估安全性:对API安全性进行定期评估,确保访问控制策略得到正确的实施,并修复已知漏洞。这包括定期审查代码、配置和依赖项,以及使用自动化工具和手动测试来识别潜在的越权漏洞。

通过遵循这些最佳实践,你可以更有效地检测和防御水平和垂直越权攻击。同时,确保定期更新你的安全策略,以应对不断变化的威胁环境。### 搜索

use MathPHP\Search;

// 搜索数字列表以找到特定索引

$list = [1, 2, 3, 4, 5];

$index   = Search::sorted($list, 2);   // 查找要插入以维护排序顺序的项的数组索引
$index   = Search::argMax($list);      // 查找最大值的数组索引
$index   = Search::nanArgMax($list);   // 查找最大值的数组索引,忽略 NANs
$index   = Search::argMin($list);      // 查找最小值的数组索引
$index   = Search::nanArgMin($list);   // 查找最小值的数组索引,忽略 NANs
$indices = Search::nonZero($list);     // 查找标量值的数组索引,这些值为非零

序列 - 基础

use MathPHP\Sequence\Basic;

$n = 5; // 序列中的元素数

// 等差数列
$d           = 2;  // 序列元素之间的差异
$a₁          = 1;  // 序列的起始数字
$progression = Basic::arithmeticProgression($n, $d, $a₁);
// [1, 3, 5, 7, 9] - 从1开始索引

// 等比数列(arⁿ⁻¹)
$a           = 2; // 标量值
$r           = 3; // 公比
$progression = Basic::geometricProgression($n, $a, $r);
// [2(3)⁰, 2(3)¹, 2(3)², 2(3)³] = [2, 6, 18, 54] - 从1开始索引

// 平方数(n²)
$squares = Basic::squareNumber($n);
// [0², 1², 2², 3², 4²] = [0, 1, 4, 9, 16] - 从0开始索引

// 立方数(n³)
$cubes = Basic::cubicNumber($n);
// [0³, 1³, 2³, 3³, 4³] = [0, 1, 8, 27, 64] - 从0开始索引

// 2的幂(2ⁿ)
$po2 = Basic::powersOfTwo($n);
// [2⁰, 2¹, 2², 2³, 2⁴] = [1,  2,  4,  8,  16] - 从0开始索引

// 10的幂(10ⁿ)
$po10 = Basic::powersOfTen($n);
// [10⁰, 10¹, 10², 10³,  10⁴] = [1, 10, 100, 1000, 10000] - 从0开始索引

// 阶乘(n!)
$fact = Basic::factorial($n);
// [0!, 1!, 2!, 3!, 4!] = [1,  1,  2,  6,  24] - 从0开始索引

// 数字和
$digit_sum = Basic::digitSum($n);
// [0, 1, 2, 3, 4] - 从0开始索引

// 数字根
$digit_root = Basic::digitalRoot($n);
// [0, 1, 2, 3, 4] - 从0开始索引

序列 - 高级

use MathPHP\Sequence\Advanced;

$n = 6; // 序列中的元素数

// 斐波那契数列(Fᵢ = Fᵢ₋₁ + Fᵢ₋₂)
$fib = Advanced::fibonacci($n);
// [0, 1, 1, 2, 3, 5] - 从0开始索引

// 卢卡斯数
$lucas = Advanced::lucasNumber($n);
// [2, 1, 3, 4, 7, 11] - 从0开始索引

// 卡特兰数
$catalan_numbers = Advanced::catalanNumber($n);
// [1, 1, 2, 5, 14, 42] - 从0开始索引

// 默尼数
$muenchhausen_numbers = Advanced::muenchhausenNumber($n);
// [0, 1, 5, 153, 370, 371] - 从0开始索引

// 素数
$primes = Advanced::primes($n);
// [2, 3, 5, 7, 11, 13] - 从0开始索引

// 合数
$composites = Advanced::composites($n);
// [4, 6, 8, 9, 10, 12] - 从0开始索引

// 四次幂
$fourth_powers = Advanced::fourthPowers($n);
// [0⁴, 1⁴, 2⁴, 3⁴, 4⁴, 5⁴] = [0, 1, 16, 81, 256, 625] - 从0开始索引

// 五次幂
$fifth_powers = Advanced::fifthPowers($n);
// [0⁵, 1⁵, 2⁵, 3⁵, 4⁵, 5⁵] = [0, 1, 32, 243, 1024, 3125] - 从0开始索引

// 第n个三角数
$triangles = Advanced::triangles($n);
// [0, 1, 3, 6, 10, 15] - 从0开始索引

// 第n个四边形数
$quadrilaterals = Advanced::quadrilaterals($n);
// [0, 1, 5, 12, 22, 35] - 从0开始索引

// 五边形数
$pentagonal_numbers = Advanced::pentagonalNumber($n);
// [0, 1, 5, 12, 22, 35] - 从0开始索引

// 六边形数
$hexagonal_numbers = Advanced::hexagonalNumber($n);
// [0, 1, 6, 15, 28, 45] - 从0开始索引

// 第n个三角形数
$triangular_numbers = Advanced::triangularNumber($n);
// [0, 1, 3, 6, 10, 15] - 从0开始索引

// 平方和
$square_sum = Advanced::squareSum($n);
// [0, 1, 5, 14, 30, 55] - 从0开始索引

// 立方和
$cube_sum = Advanced::cubeSum($n);
// [0, 1, 9, 36, 100, 225] - 从0开始索引
```### 集合论
```php
use MathPHP\SetTheory\Set;
use MathPHP\SetTheory\ImmutableSet;

// 集合和不可变集合
$A = new Set([1, 2, 3]);          // 可以添加和删除成员
$B = new ImmutableSet([3, 4, 5]); // 创建后无法修改集合

// 基本集合数据
$set         = $A->asArray();
$cardinality = $A->length();
$bool        = $A->isEmpty();

// 集合成员资格
$true = $A->isMember(2);
$true = $A->isNotMember(8);

// 添加和删除成员
$A->add(4);
$A->add(new Set(['a', 'b']));
$A->addMulti([5, 6, 7]);
$A->remove(7);
$A->removeMulti([5, 6]);
$A->clear();

// 集合属性与其他集合比较 - 返回布尔值
$bool = $A->isDisjoint($B);
$bool = $A->isSubset($B);         // A ⊆ B
$bool = $A->isProperSubset($B);   // A ⊆ B & A ≠ B
$bool = $A->isSuperset($B);       // A ⊇ B
$bool = $A->isProperSuperset($B); // A ⊇ B & A ≠ B

// 与其他集合的集合操作 - 返回新的集合
$A∪B  = $A->union($B);
$A∩B  = $A->intersect($B);
$A\B = $A->difference($B);          // 相对补集
$AΔB  = $A->symmetricDifference($B);
$A×B  = $A->cartesianProduct($B);

// 其他集合操作
$P⟮A⟯ = $A->powerSet();
$C   = $A->copy();

// 打印集合
print($A); // Set{1, 2, 3, 4, Set{a, b}}

// PHP 接口
$n = count($A);                 // Countable
foreach ($A as $member) { ... } // Iterator

// 流畅接口
$A->add(5)->add(6)->remove(4)->addMulti([7, 8, 9]);

统计学 - ANOVA

use MathPHP\Statistics\ANOVA;

// One-way ANOVA
$sample1 = [1, 2, 3];
$sample2 = [3, 4, 5];
$sample3 = [5, 6, 7];
   ⋮            ⋮

$anova = ANOVA::oneWay($sample1, $sample2, $sample3);
print_r($anova);
/* Array (
    [ANOVA] => Array (             // ANOVA hypothesis test summary data
            [treatment] => Array (
                    [SS] => 24     // Sum of squares (between)
                    [df] => 2      // Degrees of freedom
                    [MS] => 12     // Mean squares
                    [F]  => 12     // Test statistic
                    [P]  => 0.008  // P value
                )
            [error] => Array (
                    [SS] => 6      // Sum of squares (within)
                    [df] => 6      // Degrees of freedom
                    [MS] => 1      // Mean squares
                )
            [total] => Array (
                    [SS] => 30     // Sum of squares (total)
                    [df] => 8      // Degrees of freedom
                )
        )
    [total_summary] => Array (     // Total summary data
            [n]        => 9
            [sum]      => 36
            [mean]     => 4
            [SS]       => 174
            [variance] => 3.75
            [sd]       => 1.9364916731037
            [sem]      => 0.6454972243679
        )
    [data_summary] => Array (      // Data summary (each input sample)
            [0] => Array ([n] => 3 [sum] => 6  [mean] => 2 [SS] => 14  [variance] => 1 [sd] => 1 [sem] => 0.57735026918963)
            [1] => Array ([n] => 3 [sum] => 12 [mean] => 4 [SS] => 50  [variance] => 1 [sd] => 1 [sem] => 0.57735026918963)
            [2] => Array ([n] => 3 [sum] => 18 [mean] => 6 [SS] => 110 [variance] => 1 [sd] => 1 [sem] => 0.57735026918963)
        )
) */

// Two-way ANOVA
/*        | Factor B₁ | Factor B₂ | Factor B₃ | ⋯
Factor A₁ |  4, 6, 8  |  6, 6, 9  |  8, 9, 13 | ⋯
Factor A₂ |  4, 8, 9  | 7, 10, 13 | 12, 14, 16| ⋯
    ⋮           ⋮           ⋮           ⋮         */
$factorA₁ = [
  [4, 6, 8],    // Factor B₁
  [6, 6, 9],    // Factor B₂
  [8, 9, 13],   // Factor B₃
];
$factorA₂ = [
  [4, 8, 9],    // Factor B₁
  [7, 10, 13],  // Factor B₂
  [12, 14, 16], // Factor B₃
];
       ⋮

$anova = ANOVA::twoWay($factorA₁, $factorA₂);
print_r($anova);
/* Array (
    [ANOVA] => Array (          // ANOVA hypothesis test summary data
            [factorA] => Array (
                    [SS] => 32                 // Sum of squares
                    [df] => 1                  // Degrees of freedom
                    [MS] => 32                 // Mean squares
                    [F]  => 5.6470588235294    // Test statistic
                    [P]  => 0.034994350619895  // P value
                )
            [factorB] => Array (
                    [SS] => 93                 // Sum of squares
                    [df] => 2                  // Degrees of freedom
                    [MS] => 46.5               // Mean squares
                    [F]  => 8.2058823529412    // Test statistic
                    [P]  => 0.0056767297582031 // P value
                )
            [interaction] => Array (
                    [SS] => 7                  // Sum of squares
                    [df] => 2                  // Degrees of freedom
                    [MS] => 3.5                // Mean squares
                    [F]  => 0.61764705882353   // Test statistic
                    [P]  => 0.5555023440712    // P value
                )
            [error] => Array (
                    [SS] => 68                 // Sum of squares (within)
                    [df] => 12                 // Degrees of freedom
                    [MS] => 5.6666666666667    // Mean squares
                )
            [total] => Array (
                    [SS] => 200                // Sum of squares (total)
                    [df] => 17                 // Degrees of freedom
                )
        )
    [total_summary] => Array (    // Total summary data
            [n]        => 18
            [sum]      => 162
            [mean]     => 9
            [SS]       => 1658
            [variance] => 11.764705882353
            [sd]       => 3.4299717028502
            [sem]      => 0.80845208345444
        )
    [summary_factorA]     => Array ( ... )   // Summary data of factor A
    [summary_factorB]     => Array ( ... )   // Summary data of factor B
    [summary_interaction] => Array ( ... )   // Summary data of interactions of factors A and B
) */

统计学 - 平均数

use MathPHP\Statistics\Average;

$numbers = [13, 18, 13, 14, 13, 16, 14, 21, 13];

// 均值、中位数、众数
$mean   = Average::mean($numbers);
$median = Average::median($numbers);
$mode   = Average::mode($numbers); // 返回一个数组 - 可能具有多峰性

// 加权平均数
$weights       = [12, 1, 23, 6, 12, 26, 21, 12, 1];
$weighted_mean = Average::weightedMean($numbers, $weights)

// 数字列表的其他平均数
$geometric_mean      = Average::geometricMean($numbers);
$harmonic_mean       = Average::harmonicMean($numbers);
$contraharmonic_mean = Average::contraharmonicMean($numbers);
$quadratic_mean      = Average::quadraticMean($numbers);  // 与 rootMeanSquare 相同
$root_mean_square    = Average::rootMeanSquare($numbers); // 与 quadraticMean 相同
$trimean             = Average::trimean($numbers);
$interquartile_mean  = Average::interquartileMean($numbers); // 与 iqm 相同
$interquartile_mean  = Average::iqm($numbers);               // 与 interquartileMean 相同
$cubic_mean          = Average::cubicMean($numbers);

// 截尾均值(修剪均值)
$trim_percent   = 25;  // 剪掉分布两端的 25% 观测值
$truncated_mean = Average::truncatedMean($numbers, $trim_percent);

// 广义平均数(幂平均数)
$p                = 2;
$generalized_mean = Average::generalizedMean($numbers, $p); // 与 powerMean 相同
$power_mean       = Average::powerMean($numbers, $p);       // 与 generalizedMean 相同

// Lehmer 均值
$p           = 3;
$lehmer_mean = Average::lehmerMean($numbers, $p);

// 移动平均数
$n       = 3;
$weights = [3, 2, 1];
$SMA     = Average::simpleMovingAverage($numbers, $n);             // 3 点移动平均数
$CMA     = Average::cumulativeMovingAverage($numbers);
$WMA     = Average::weightedMovingAverage($numbers, $n, $weights);
$EPA     = Average::exponentialMovingAverage($numbers, $n);

// 两个数字的平均数
[$x, $y]       = [24, 6];
$agm           = Average::arithmeticGeometricMean($x, $y); // 与 agm 相同
$agm           = Average::agm($x, $y);                     // 与 arithmeticGeometricMean 相同
$log_mean      = Average::logarithmicMean($x, $y);
$heronian_mean = Average::heronianMean($x, $y);
$identric_mean = Average::identricMean($x, $y);

// 平均数报告
$averages = Average::describe($numbers);
print_r($averages);
/* Array (
    [mean]                => 15
    [median]              => 14
    [mode]                => Array ( [0] => 13 )
    [geometric_mean]      => 14.789726414533
    [harmonic_mean]       => 14.605077399381
    [contraharmonic_mean] => 15.474074074074
    [quadratic_mean]      => 15.235193176035
    [trimean]             => 14.5
    [iqm]                 => 14
    [cubic_mean]          => 15.492307432707
) */
```### 统计学 - 循环

```php
use MathPHP\Statistics\Circular;

$angles = [1.51269877, 1.07723915, 0.81992282];

$θ = Circular::mean($angles);
$R = Circular::resultantLength($angles);
$ρ = Circular::meanResultantLength($angles);
$V = Circular::variance($angles);
$ν = Circular::standardDeviation($angles);

// 循环统计信息
$stats = Circular::describe($angles);
print_r($stats);
/* Array (
    [n]                     => 3
    [mean]                  => 1.1354043006436
    [resultant_length]      => 2.8786207547493
    [mean_resultant_length] => 0.9595402515831
    [variance]              => 0.040459748416901
    [sd]                    => 0.28740568481722
); */

统计学 - 相关性

use MathPHP\Statistics\Correlation;

$X = [1, 2, 3, 4, 5];
$Y = [2, 3, 4, 4, 6];

// 协方差
$σxy = Correlation::covariance($X, $Y);  // 有可选参数,可设置总体(默认为样本协方差)

// 加权协方差
$w    = [2, 3, 1, 1, 5];
$σxyw = Correlation::weightedCovariance($X, $Y, $w);

// r - 皮尔逊积矩相关系数(Pearson's r)
$r = Correlation::r($X, $Y);  // 有可选参数,可设置总体(默认为样本相关系数)

// 加权相关系数
$rw = Correlation::weightedCorrelationCoefficient($X, $Y, $w);

// R² - 决定系数
$R² = Correlation::r2($X, $Y);  // 有可选参数,可设置总体(默认为样本决定系数)

// τ - Kendall秩相关系数(Kendall's tau)
$τ = Correlation::kendallsTau($X, $Y);

// ρ - Spearman秩相关系数(Spearman's rho)
$ρ = Correlation::spearmansRho($X, $Y);

// 描述性相关性报告
$stats = Correlation::describe($X, $Y);
print_r($stats);
/* Array (
    [cov] => 2.25
    [r]   => 0.95940322360025
    [r2]  => 0.92045454545455
    [tau] => 0.94868329805051
    [rho] => 0.975
) */

// 置信椭圆 - 创建一个包围数据的椭圆,指定标准差
$sd           = 1;
$num_points   = 11; // 可选参数,指定椭圆点数
$ellipse_data = Correlation::confidenceEllipse($X, $Y, $sd, $num_points);

统计学 - 描述性

use MathPHP\Statistics\Descriptive;

$numbers = [13, 18, 13, 14, 13, 16, 14, 21, 13];

// 范围和中程数
$range    = Descriptive::range($numbers);
$midrange = Descriptive::midrange($numbers);

// 方差(总体和样本)
$σ² = Descriptive::populationVariance($numbers); // n自由度
$S² = Descriptive::sampleVariance($numbers);     // n-1自由度

// 方差(自定义自由度)
$df = 5;                                    // 自由度
$S² = Descriptive::variance($numbers, $df); // 可指定自定义自由度

// 加权样本方差
$weights = [0.1, 0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1];
$σ²w     = Descriptive::weightedSampleVariance($numbers, $weights, $biased = false);

// 标准差(用于样本和总体)
$σ = Descriptive::populationStandardDeviation($numbers); // n自由度
$S = Descriptive::standardDeviation($numbers);           // n-1自由度

// 标准差(自定义自由度)
$df = 5;                                  // 自由度
$S  = Descriptive::standardDeviation($numbers, $df); // 可指定自定义自由度

// 加权样本标准差
$weights = [0.1, 0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1];
$σw     = Descriptive::weightedSampleStandardDeviation($numbers, $weights, $biased = false);

// 平均值
$mean = Descriptive::mean($numbers);

// 加权平均值
$weights = [0.1, 0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1];
$mean_w = Descriptive::weightedMean($numbers, $weights);

// 中位数
$median = Descriptive::median($numbers);

// 众数
$mode = Descriptive::mode($numbers);

// 四分位数
$quartiles = Descriptive::quartiles($numbers);

// 描述性统计信息
$stats = Descriptive::describe($numbers);
print_r($stats);
/* Array (
    [n]          => 9
    [mean]       => 15
    [median]     => 14
    [mode]       => Array ( [0] => 13 )
    [range]      => 8
    [midrange]   => 17
    [variance]   => 8.25
    [sd]         => 2.872281323269
    [cv]         => 0.191485678507
    [skewness]   => 0.311310843153
    [ses]        => 0.95742710775634
    [kurtosis]   => -1.29767656687
    [sek]        => 1.08515292151
    [quartiles]  => Array ( [0] => 13 [1] => 14 [2] => 18 )
    [iqr]        => 4
    [mad]        => 2
    [trimmed_mean] => 14.6
) */

统计学 - 偏差

use MathPHP\Statistics\Deviation;

$numbers = [1, 2, 3, 4, 5];

// 平均绝对偏差
$average_deviation = Deviation::meanAbsoluteDeviation($numbers);

// 方差(样本和总体)
$σ² = Deviation::populationVariance($numbers); // n自由度
$S² = Deviation::sampleVariance($numbers);     // n-1自由度

// 标准偏差(样本和总体)
$σ = Deviation::populationStandardDeviation($numbers); // n自由度
$S = Deviation::standardDeviation($numbers);           // n-1自由度

// 马氏距离
$X        = [1, 2, 3, 4, 5];
$Y        = [1.5, 2.5, 3.5, 4.5, 5.5];
$distance = Deviation::mahalanobisDistance($X, $Y, $Σ = null, $center = null);

矩阵 - 基本运算

use MathPHP\LinearAlgebra\Matrix;

$A = Matrix::create([
    [1, 2],
    [3, 4],
    [5, 6]
]);

$B = Matrix::create([
    [2, 2, 2],
    [2, 2, 2]
]);

$C = Matrix::create([
    [1, 2],
    [3, 4]
]);

$D = Matrix::create([
    [1, 2],
    [3, 4],
    [5, 6]
]);

// 矩阵加法
$AplusB = $A->add($B);

// 矩阵减法
$AminusC = $A->subtract($C);

// 矩阵乘法
$AB = $A->multiply($### 统计学 - 距离
```php
use MathPHP\Statistics\Distance;

// 概率分布
$X = [0.2, 0.5, 0.3];
$Y = [0.1, 0.4, 0.5];

// 距离
$DB⟮X、Y⟯   = Distance::bhattacharyya($X, $Y);
$H⟮X、Y⟯    = Distance::hellinger($X, $Y);
$D⟮X、Y⟯    = Distance::minkowski($X, $Y, $p = 2);
$d⟮X、Y⟯    = Distance::euclidean($X, $Y);          // L² 距离
$d₁⟮X、Y⟯   = Distance::manhattan($X, $Y);          // L¹ 距离, 凸型距离, 城市街区距离
$JSD⟮X‖Y⟯   = Distance::jensenShannon($X, $Y);
$d⟮X、Y⟯    = Distance::canberra($X, Y);
brayCurtis = Distance::brayCurtis($X, $Y);
$cosine    = Distance::cosine($X, $Y);
$cos⟮α⟯     = Distance::cosineSimilarity($X, $Y);

// 马氏距离
$x    = new Matrix([[6], [5]]);
$data = new Matrix([
    [4, 4, 5, 2, 3, 6, 9, 7, 4, 5],
    [3, 7, 5, 7, 9, 5, 6, 2, 2, 7],
]);
$otherData = new Matrix([
    [4, 4, 5, 2, 3, 6, 9, 7, 4, 5],
    [3, 7, 5, 7, 9, 5, 6, 2, 2, 7],
]);
$y = new Matrix([[2], [2]]);
$D = Distance::mahalanobis($x, $data);          // 距离 $x 到数据的中心的马氏距离。
$D = Distance::mahalanobis($x, $data, $y);      // 使用数据的马氏距离计算 $x 和 $y 之间的马氏距离。
$D = Distance::mahalanobis($data, $otherData);  // 两组数据的中心之间的马氏距离。

统计学 - 分布

use MathPHP\Statistics\Distribution;

$grades = ['A', 'A', 'B', 'B', 'B', 'B', 'C', 'C', 'D', 'F'];

// 频率分布 (频率和相对频率)
$frequencies          = Distribution::frequency($grades);         // [ A => 2,   B => 4,   C => 2,   D => 1,   F => 1   ]
$relative_frequencies = Distribution::relativeFrequency($grades); // [ A => 0.2, B => 0.4, C => 0.2, D => 0.1, F => 0.1 ]

// 累计频率分布 (累计频率和累计相对频率)
$cumulative_frequencies          = Distribution::cumulativeFrequency($grades);         // [ A => 2,   B => 6,   C => 8,   D => 9,   F => 10  ]
$cumulative_relative_frequencies = Distribution::cumulativeRelativeFrequency($grades); // [ A => 0.2, B => 0.6, C => 0.8, D => 0.9, F => 1   ]

// 数据排名
$values                       = [1, 2, 2, 3];
$ordinal_ranking              = Distribution::ordinalRanking($values);              // 1, 2, 3, 4
$standard_competition_ranking = Distribution::standardCompetitionRanking($values);  // 1, 2, 2, 4
$modified_competition_ranking = Distribution::modifiedCompetitionRanking($values);  // 1, 3, 3, 4
$fractional_ranking           = Distribution::fractionalRanking($values);           // 1, 2.5, 2.5, 4

// 统计量
$data = [1, 2, 3, 4, 5];
$mean = Distribution::mean($data);             // 3
$median = Distribution::median($data);         // 3
$mode = Distribution::mode($data);             // null
$range = Distribution::range($data);           // 4
$variance = Distribution::populationVariance($data);   // 2.5
$stdev = Distribution::populationStandardDeviation($data);  // 1.5811388300842
$coefvar = Distribution::coefficientOfVariation($data); // 0.52704627669473
```### 统计学 - 实验
```php
use MathPHP\Statistics\Experiment;

$a = 28;   // 暴露并存在事件
$b = 129;  // 暴露但不存在事件
$c = 4;    // 非暴露但存在事件
$d = 133;  // 非暴露且不存在事件

// 风险比率(相对风险)- RR
$RR = Experiment::riskRatio($a, $b, $c, $d);
// ['RR' => 6.1083, 'ci_lower_bound' => 2.1976, 'ci_upper_bound' => 16.9784, 'p' => 0.0005]

// 比率比(OR)
$OR = Experiment::oddsRatio($a, $b, $c, $d);
// ['OR' => 7.2171, 'ci_lower_bound' => 2.4624, 'ci_upper_bound' => 21.1522, 'p' => 0.0003]

// 似然比(正向和负向)
$LL = Experiment::likelihoodRatio($a, $b, $c, $d);
// ['LL+' => 7.4444, 'LL-' => 0.3626]

$sensitivity = 0.67;
$specificity = 0.91;
$LL          = Experiment::likelihoodRatioSS($sensitivity, $specificity);

统计学 - 核密度估计

use MathPHP\Statistics\KernelDensityEstimation

$data = [-2.76, -1.09, -0.5, -0.15, 0.22, 0.69, 1.34, 1.75];
$x    = 0.5;

// 使用默认带宽(正态分布近似)和核函数(标准正态)的密度估计器
$kde     = new KernelDensityEstimation($data);
$density = $kde->evaluate($x)

// 自定义带宽
$h = 0.1;
$kde->setBandwidth($h);

// 内置核函数库
$kde->setKernelFunction(KernelDensityEstimation::STANDARD_NORMAL);
$kde->setKernelFunction(KernelDensityEstimation::NORMAL);
$kde->setKernelFunction(KernelDensityEstimation::UNIFORM);
$kde->setKernelFunction(KernelDensityEstimation::TRIANGULAR);
$kde->setKernelFunction(KernelDensityEstimation::EPANECHNIKOV);
$kde->setKernelFunction(KernelDensityEstimation::TRICUBE);

// 设置自定义核函数(用户提供的可调用函数)
$kernel = function ($x) {
  if (abs($x) > 1) {
      return 0;
  } else {
      return 70 / 81 * ((1 - abs($x) ** 3) ** 3);
  }
};
$kde->setKernelFunction($kernel);

// 所有自定义选项都可以在构造函数中完成
$kde = new KernelDesnsityEstimation($data, $h, $kernel);

统计学 - 多元 - 主成分分析

use MathPHP\Statistics\Multivariate\PCA;
use MathPHP\LinearAlgebra\MatrixFactory;

// 给定
$matrix = MatrixFactory::create($data);  // 可能相关变量的观测值
$center = true;                          // 数据均值中心化
$scale  = true;                          // 数据标准化

// 建立一个主成分分析模型进行探索
$model = new PCA($matrix, $center, $scale);

// 主成分分析模型的分数和载荷
$scores      = $model->getScores();       // 载荷矩阵的转换标准化数据矩阵
$loadings    = $model->getLoadings();     // 相关矩阵的单位特征向量矩阵
$eigenvalues = $model->getEigenvalues();  // 组件的特征值向量

// 残差、极限、临界值等
$R²         = $model->getR2();           // R²值数组
$cumR²      = $model->getCumR2();        // 累积R²值数组
$Q          = $model->getQResiduals();   // Q残差矩阵
$T²         = $model->getT2Distances();  // T²距离矩阵
$T²Critical = $model->getCriticalT2();   // T²的关键限制数组
$QCritical  = $model->getCriticalQ();    // Q的关键限制数组

统计学 - 多元 - 偏最小二乘回归

use MathPHP\Statistics\Multivariate\PLS;
use MathPHP\LinearAlgebra\MatrixFactory;
use MathPHP\SampleData;

// 给定
$cereal = new SampleData\Cereal();
$X      = MatrixFactory::createNumeric($cereal->getXData());
$Y      = MatrixFactory::createNumeric($cereal->getYData());

// 建立一个偏最小二乘回归进行探索
$numberOfComponents = 5;
$scale              = true;
$pls                = new PLS($X, $Y, $numberOfComponents, $scale);

// PLS模型数据
$C = $pls->getYLoadings();     // Y值的载荷(每个载荷列将F转换为U)
$W = $pls->getXLoadings();     // X值的载荷(每个载荷列将E转换为T)
$T = $pls->getXScores();       // X值的得分(X的潜在变量)
$U = $pls->getYScores();       // Y值的得分(Y的潜在变量)
$B = $pls->getCoefficients();  // 回归系数(最佳将E转换为F的矩阵)
$P = $pls->getProjections();   // 投影矩阵(每个投影列将T转换为Ê)

// 预测值(使用回归模型预测给定X值的新Y值)
$yPredictions = $pls->predict($xMatrix);
```### 统计学 - 异常值
```php
use MathPHP\Statistics\Outlier;

$data = [199.31, 199.53, 200.19, 200.82, 201.92, 201.95, 202.18, 245.57];
$n    = 8;    // 数据大小
$𝛼    = 0.05; // 显著性水平

// Grubb's test - 双侧检验
$grubbsStatistic = Outlier::grubbsStatistic($data, Outlier::TWO_SIDED);
$criticalValue   = Outlier::grubbsCriticalValue($𝛼, $n, Outlier::TWO_SIDED);

// Grubbs' test - 对最小值的单侧检验
$grubbsStatistic = Outlier::grubbsStatistic($data, Outlier::ONE_SIDED_LOWER);
$criticalValue   = Outlier::grubbsCriticalValue($𝛼, $n, Outlier::ONE_SIDED);

// Grubbs' test - 对最大值的单侧检验
$grubbsStatistic = Outlier::grubbsStatistic($data, Outlier::ONE_SIDED_UPPER);
$criticalValue   = Outlier::grubbsCriticalValue($𝛼, $n, Outlier::ONE_SIDED);

统计学 - 随机变量

use MathPHP\Statistics\RandomVariable;

$X = [1, 2, 3, 4];
$Y = [2, 3, 4, 5];

// 中心矩 (第n个矩)
$second_central_moment = RandomVariable::centralMoment($X, 2);
$third_central_moment  = RandomVariable::centralMoment($X, 3);

// 偏度 (总体、样本和备选一般方法)
$skewness = RandomVariable::skewness($X);            // 可选类型参数以选择偏度类型的计算。默认为样本偏度 (类似于Excel的SKEW)。
$skewness = RandomVariable::sampleSkewness($X);      // 与RandomVariable::skewness($X, RandomVariable::SAMPLE_SKEWNESS)相同 - 类似于Excel的SKEW、SAS和SPSS、R (e1071)的偏度类型2
$skewness = RandomVariable::populationSkewness($X);  // 与RandomVariable::skewness($X, RandomVariable::POPULATION_SKEWNESS)相同 - 类似于Excel的SKEW.P、经典教科书定义、R (e1071)的偏度类型1
$skewness = RandomVariable::alternativeSkewness($X); // 与RandomVariable::skewness($X, RandomVariable::ALTERNATIVE_SKEWNESS)相同 - 偏度的另一种经典定义
$SES      = RandomVariable::ses(count($X));          // 偏度的标准误差

// 峰度 (超额)
$kurtosis    = RandomVariable::kurtosis($X);           // 可选类型参数以选择峰度类型的计算。默认为总体峰度 (类似于Excel的KURT)。
$kurtosis    = RandomVariable::sampleKurtosis($X);     // 与RandomVariable::kurtosis($X, RandomVariable::SAMPLE_KURTOSIS)相同 - 类似于R (e1071)的峰度类型1
$kurtosis    = RandomVariable::populationKurtosis($X); // 与RandomVariable::kurtosis($X, RandomVariable::POPULATION_KURTOSIS)相同 - 类似于Excel的KURT、SAS和SPSS、R (e1071)的峰度类型2
$platykurtic = RandomVariable::isPlatykurtic($X);      // 如果峰度小于零,则为true
$leptokurtic = RandomVariable::isLeptokurtic($X);      // 如果峰度大于零,则为true
$mesokurtic  = RandomVariable::isMesokurtic($X);       // 如果峰度为零,则为true
$SEK         = RandomVariable::sek(count($X));         // 峰度的标准误差

// 均值的标准误差 (SEM)
$sem = RandomVariable::standardErrorOfTheMean($X); // 同sem
$sem = RandomVariable::sem($X);                    // 同standardErrorOfTheMean

// 置信区间
$μ  = 90; // 样本平均数
$n  = 9;  // 样本大小
$σ  = 36; // 标准差
$cl = 99; // 置信水平
$ci = RandomVariable::confidenceInterval($μ, $n, $σ, $cl); // 数组( [ci] => 30.91, [lower_bound] => 59.09, [upper_bound] => 120.91 )

统计学 - 回归

use MathPHP\Statistics\Regression;

$points = [[1,2], [2,3], [4,5], [5,7], [6,8]];

// Simple linear regression (least squares method)
$regression = new Regression\Linear($points);
$parameters = $regression->getParameters();          // [m => 1.2209302325581, b => 0.6046511627907]
$equation   = $regression->getEquation();            // y = 1.2209302325581x + 0.6046511627907
$y          = $regression->evaluate(5);              // Evaluate for y at x = 5 using regression equation
$ci         = $regression->ci(5, 0.5);               // Confidence interval for x = 5 with p-value of 0.5
$pi         = $regression->pi(5, 0.5);               // Prediction interval for x = 5 with p-value of 0.5; Optional number of trials parameter.
$Ŷ          = $regression->yHat();
$r          = $regression->r();                      // same as correlationCoefficient
$r²         = $regression->r2();                     // same as coefficientOfDetermination
$se         = $regression->standardErrors();         // [m => se(m), b => se(b)]
$t          = $regression->tValues();                // [m => t, b => t]
$p          = $regression->tProbability();           // [m => p, b => p]
$F          = $regression->fStatistic();
$p          = $regression->fProbability();
$h          = $regression->leverages();
$e          = $regression->residuals();
$D          = $regression->cooksD();
$DFFITS     = $regression->dffits();
$SStot      = $regression->sumOfSquaresTotal();
$SSreg      = $regression->sumOfSquaresRegression();
$SSres      = $regression->sumOfSquaresResidual();
$MSR        = $regression->meanSquareRegression();
$MSE        = $regression->meanSquareResidual();
$MSTO       = $regression->meanSquareTotal();
$error      = $regression->errorSd();                // Standard error of the residuals
$V          = $regression->regressionVariance();
$n          = $regression->getSampleSize();          // 5
$points     = $regression->getPoints();              // [[1,2], [2,3], [4,5], [5,7], [6,8]]
$xs         = $regression->getXs();                  // [1, 2, 4, 5, 6]
$ys         = $regression->getYs();                  // [2, 3, 5, 7, 8]
$ν          = $regression->degreesOfFreedom();

// Linear regression through a fixed point (least squares method)
$force_point = [0,0];
$regression  = new Regression\LinearThroughPoint($points, $force_point);
$parameters  = $regression->getParameters();
$equation    = $regression->getEquation();
$y           = $regression->evaluate(5);
$Ŷ           = $regression->yHat();
$r           = $regression->r();
$r²          = $regression->r2();
 ⋮                     ⋮

// Theil–Sen estimator (Sen's slope estimator, Kendall–Theil robust line)
$regression  = new Regression\TheilSen($points);
$parameters  = $regression->getParameters();
$equation    = $regression->getEquation();
$y           = $regression->evaluate(5);
 ⋮                     ⋮

// Use Lineweaver-Burk linearization to fit data to the Michaelis–Menten model: y = (V * x) / (K + x)
$regression  = new Regression\LineweaverBurk($points);
$parameters  = $regression->getParameters();  // [V, K]
$equation    = $regression->getEquation();    // y = Vx / (K + x)
$y           = $regression->evaluate(5);
 ⋮                     ⋮

// Use Hanes-Woolf linearization to fit data to the Michaelis–Menten model: y = (V * x) / (K + x)
$regression  = new Regression\HanesWoolf($points);
$parameters  = $regression->getParameters();  // [V, K]
$equation    = $regression->getEquation();    // y = Vx / (K + x)
$y           = $regression->evaluate(5);
 ⋮                     ⋮

// Power law regression - power curve (least squares fitting)
$regression = new Regression\PowerLaw($points);
$parameters = $regression->getParameters();   // [a => 56.483375436574, b => 0.26415375648621]
$equation   = $regression->getEquation();     // y = 56.483375436574x^0.26415375648621
$y          = $regression->evaluate(5);
 ⋮                     ⋮

// LOESS - Locally Weighted Scatterplot Smoothing (Local regression)
$α          = 1/3;                         // Smoothness parameter
$λ          = 1;                           // Order of the polynomial fit
$regression = new Regression\LOESS($points, $α, $λ);
$y          = $regression->evaluate(5);
$Ŷ          = $regression->yHat();
 ⋮                     ⋮

统计学 - 显著性测试

use MathPHP\Statistics\Significance;

// Z test - One sample (z and p values)
$Hₐ = 20;   // Alternate hypothesis (M Sample mean)
$n  = 200;  // Sample size
$H₀ = 19.2; // Null hypothesis (μ Population mean)
$σ  = 6;    // SD of population (Standard error of the mean)
$z  = Significance:zTest($Hₐ, $n, $H₀, $σ);           // Same as zTestOneSample
$z  = Significance:zTestOneSample($Hₐ, $n, $H₀, $σ);  // Same as zTest
/* [
  'z'  => 1.88562, // Z score
  'p1' => 0.02938, // one-tailed p value
  'p2' => 0.0593,  // two-tailed p value
] */

// Z test - Two samples (z and p values)
$μ₁ = 27;   // Sample mean of population 1
$μ₂ = 33;   // Sample mean of population 2
$n₁ = 75;   // Sample size of population 1
$n₂ = 50;   // Sample size of population 2
$σ₁ = 14.1; // Standard deviation of sample mean 1
$σ₂ = 9.5;  // Standard deviation of sample mean 2
$z  = Significance::zTestTwoSample($μ₁, $μ₂, $n₁, $n₂, $σ₁, $σ₂);
/* [
  'z'  => -2.36868418147285,  // z score
  'p1' => 0.00893,            // one-tailed p value
  'p2' => 0.0179,             // two-tailed p value
] */

// Z score
$M = 8; // Sample mean
$μ = 7; // Population mean
$σ = 1; // Population SD
$z = Significance::zScore($M, $μ, $σ);

// T test - One sample (from sample data)
$a     = [3, 4, 4, 5, 5, 5, 6, 6, 7, 8]; // Data set
$H₀    = 300;                            // Null hypothesis (μ₀ Population mean)
$tTest = Significance::tTest($a, $H₀)
print_r($tTest);
/* Array (
    [t]    => 0.42320736951516  // t score
    [df]   => 9                 // degrees of freedom
    [p1]   => 0.34103867713806  // one-tailed p value
    [p2]   => 0.68207735427613  // two-tailed p value
    [mean] => 5.3               // sample mean
    [sd]   => 1.4944341180973   // standard deviation
) */

// T test - One sample (from summary data)
$Hₐ    = 280; // Alternate hypothesis (M Sample mean)
$s     = 50;  // Standard deviation of sample
$n     = 15;  // Sample size
$H₀    = 300; // Null hypothesis (μ₀ Population mean)
$tTest = Significance::tTestOneSampleFromSummaryData($Hₐ, $s, $n, $H₀);
print_r($tTest);
/* Array (
    [t]    => -1.549193338483    // t score
    [df]   => 14                 // degreees of freedom
    [p1]   => 0.071820000122611  // one-tailed p value
    [p2]   => 0.14364000024522   // two-tailed p value
    [mean] => 280                // sample mean
    [sd]   => 50                 // standard deviation
) */

// T test - Two samples (from sample data)
$x₁    = [27.5, 21.0, 19.0, 23.6, 17.0, 17.9, 16.9, 20.1, 21.9, 22.6, 23.1, 19.6, 19.0, 21.7, 21.4];
$x₂    = [27.1, 22.0, 20.8, 23.4, 23.4, 23.5, 25.8, 22.0, 24.8, 20.2, 21.9, 22.1, 22.9, 20.5, 24.4];
$tTest = Significance::tTest($x₁, $x₂);
print_r($tTest);
/* Array (
    [t]     => -2.4553600286929   // t score
    [df]    => 24.988527070145    // degrees of freedom
    [p1]    => 0.010688914613979  // one-tailed p value
    [p2]    => 0.021377829227958  // two-tailed p value
    [mean1] => 20.82              // mean of sample x₁
    [mean2] => 22.98667           // mean of sample x₂
    [sd1]   => 2.804894           // standard deviation of x₁
    [sd2]   => 1.952605           // standard deviation of x₂
) */

// T test - Two samples (from summary data)
$μ₁    = 42.14; // Sample mean of population 1
$μ₂    = 43.23; // Sample mean of population 2
$n₁    = 10;    // Sample size of population 1
$n₂    = 10;    // Sample size of population 2
$σ₁    = 0.683; // Standard deviation of sample mean 1
$σ₂    = 0.750; // Standard deviation of sample mean 2
$tTest = Significance::tTestTwoSampleFromSummaryData($μ₁, $μ₂, $n₁, $n₂, $σ₁, $σ₂);
print_r($tTest);
/* Array (
   [t] => -3.3972305988708     // t score
   [df] => 17.847298548027     // degrees of freedom
   [p1] => 0.0016211251126198  // one-tailed p value
   [p2] => 0.0032422502252396  // two-tailed p value
   [mean1] => 42.14
   [mean2] => 43.23
   [sd1] => 0.6834553
   [sd2] => 0.7498889
] */

// T score
$Hₐ = 280; // Alternate hypothesis (M Sample mean)
$s  = 50;  // SD of sample
$n  = 15;  // Sample size
$H₀ = 300; // Null hypothesis (μ₀ Population mean)
$t  = Significance::tScore($Hₐ, $s, $n, $H);

// χ² test (chi-squared goodness of fit test)
$observed = [4, 6, 17, 16, 8, 9];
$expected = [10, 10, 10, 10, 10, 10];
$χ²       = Significance::chiSquaredTest($observed, $expected);
// ['chi-square' => 14.2, 'p' => 0.014388]

三角函数

use MathPHP\Trigonometry;

$n      = 9;
$points = Trigonometry::unitCircle($n); // 产生沿单位圆的n个点

单元测试

超过100%的代码覆盖率!

MathPHP具有数千个单元测试,直接测试具有多个数据输入的单个函数,以实现100%的测试覆盖率。 MathPHP单元测试还测试了数学公理,间接测试了同一函数的多个不同方式,以确保这些数学属性根据公理都能正确计算。

$ cd tests
$ phpunit

标准MathPHP 符合以下标准:

许可证

MathPHP 使用 MIT 许可证。

标签:工具分享