Skip to content

Math 数学函数

PHP 提供了丰富的数学函数,涵盖基础算术、三角函数、对数、取整、随机数等。这些函数大多数直接映射到 C 标准库的数学函数,性能高效。本节将全面讲解 PHP 数学函数的用法。

前置知识

阅读本节前,建议先了解:PHP 类型系统运算符

基础算术

常用数学函数

php
<?php
declare(strict_types=1);

// 绝对值
echo abs(-5) . PHP_EOL;      // 5
echo abs(-3.14) . PHP_EOL;    // 3.14

// 最大值 / 最小值
echo max(1, 5, 3) . PHP_EOL;     // 5
echo min(1, 5, 3) . PHP_EOL;     // 1
echo max([1, 5, 3]) . PHP_EOL;   // 5

// 取整
echo ceil(4.1) . PHP_EOL;     // 5(向上取整)
echo ceil(-4.1) . PHP_EOL;    // -4
echo floor(4.9) . PHP_EOL;    // 4(向下取整)
echo floor(-4.9) . PHP_EOL;   // -5
echo round(4.4) . PHP_EOL;    // 4(四舍五入)
echo round(4.5) . PHP_EOL;    // 5
echo round(4.456, 2) . PHP_EOL; // 4.46(指定精度)

// 整除(PHP 7+)
echo intdiv(10, 3) . PHP_EOL; // 3
echo intdiv(-10, 3) . PHP_EOL; // -3

// 取余
echo fmod(10.5, 3) . PHP_EOL;  // 1.5
echo 10 % 3 . PHP_EOL;         // 1

// 幂运算
echo pow(2, 10) . PHP_EOL;      // 1024
echo 2 ** 10 . PHP_EOL;         // 1024
echo sqrt(144) . PHP_EOL;       // 12
echo exp(1) . PHP_EOL;          // 2.71828...

// 对数
echo log(M_E) . PHP_EOL;        // 1(自然对数)
echo log10(100) . PHP_EOL;      // 2(以10为底)
echo log2(1024) . PHP_EOL;      // 10(以2为底)

数学常量

php
<?php
declare(strict_types=1);

echo M_PI      . PHP_EOL; // 3.1415926535898 圆周率
echo M_E       . PHP_EOL; // 2.718281828459  自然对数底
echo M_LN2     . PHP_EOL; // 0.6931471805599  ln(2)
echo M_LN10    . PHP_EOL; // 2.302585092994   ln(10)
echo M_LOG2E   . PHP_EOL; // 1.442695040889   log2(e)
echo M_LOG10E  . PHP_EOL; // 0.4342944819032  log10(e)
echo M_SQRT2   . PHP_EOL; // 1.414213562373   sqrt(2)
echo M_INF     . PHP_EOL; // INF 无穷大
echo M_1_PI    . PHP_EOL; // 1/PI
echo M_2_PI    . PHP_EOL; // 2/PI

三角函数

php
<?php
declare(strict_types=1);

// 弧度/角度转换
$deg = 45;
$rad = deg2rad($deg);
echo "{$deg}度 = {$rad} 弧度" . PHP_EOL;
echo rad2deg(M_PI) . " 度" . PHP_EOL;

// 三角函数(参数为弧度)
echo sin($rad) . PHP_EOL;       // 正弦
echo cos($rad) . PHP_EOL;       // 余弦
echo tan($rad) . PHP_EOL;       // 正切

// 反三角函数
echo asin(0.5) . PHP_EOL;       // 反正弦
echo acos(0.5) . PHP_EOL;       // 反余弦
echo atan(1) . PHP_EOL;          // 反正切
echo atan2(1, 1) . PHP_EOL;     // 两参数反正切

// 双曲函数
echo sinh(1) . PHP_EOL;          // 双曲正弦
echo cosh(1) . PHP_EOL;          // 双曲余弦
echo tanh(1) . PHP_EOL;          // 双曲正切

// 勾股定理
function hypotenuse(float $a, float $b): float
{
    return sqrt($a * $a + $b * $b);
}
echo hypotenuse(3, 4) . PHP_EOL; // 5

// PHP 内置 hypot()
echo hypot(3, 4) . PHP_EOL; // 5

数值工具

范围检查

php
<?php
declare(strict_types=1);

// 限制范围
echo max(0, min(255, -50)) . PHP_EOL; // 0 (限制在 0~255)

// clamp 函数
function clamp(float $value, float $min, float $max): float
{
    return max($min, min($max, $value));
}

echo clamp(150, 0, 100) . PHP_EOL; // 100
echo clamp(-5, 0, 100) . PHP_EOL;  // 0
echo clamp(50, 0, 100) . PHP_EOL;  // 50

// NaN 检查
echo is_nan(sqrt(-1)) ? 'NaN' : 'Number' . PHP_EOL;

// 有限值检查
echo is_finite(1.0) ? 'finite' : 'infinite' . PHP_EOL;
echo is_infinite(log(0)) ? 'infinite' : 'finite' . PHP_EOL;

数字格式化

php
<?php
declare(strict_types=1);

// number_format - 千位分隔格式化
echo number_format(1234567.89, 2, '.', ',') . PHP_EOL; // 1,234,567.89
echo number_format(1234567.89, 0) . PHP_EOL;              // 1,234,568

// 进制转换
echo base_convert('255', 10, 16) . PHP_EOL;  // ff
echo base_convert('ff', 16, 10) . PHP_EOL;   // 255
echo decbin(255) . PHP_EOL;                   // 11111111
echo decoct(255) . PHP_EOL;                   // 377
echo dechex(255) . PHP_EOL;                   // ff
echo hexdec('ff') . PHP_EOL;                  // 255
echo bindec('11111111') . PHP_EOL;            // 255
echo octdec('377') . PHP_EOL;                  // 255

实战示例

数学计算器

php
<?php
declare(strict_types=1);

class Calculator
{
    public static function average(array $numbers): float
    {
        if (empty($numbers)) {
            return 0.0;
        }
        return array_sum($numbers) / count($numbers);
    }

    public static function median(array $numbers): float
    {
        sort($numbers);
        $count = count($numbers);
        $mid = (int) floor($count / 2);

        return ($count % 2 === 0)
            ? ($numbers[$mid - 1] + $numbers[$mid]) / 2
            : $numbers[$mid];
    }

    public static function standardDeviation(array $numbers): float
    {
        $avg = self::average($numbers);
        $squares = array_map(fn($n) => pow($n - $avg, 2), $numbers);
        return sqrt(array_sum($squares) / count($numbers));
    }

    public static function percentage(float $value, float $total, int $decimals = 1): string
    {
        if ($total === 0.0) {
            return '0%';
        }
        $pct = ($value / $total) * 100;
        return round($pct, $decimals) . '%';
    }
}

$data = [85, 90, 78, 92, 88, 95, 80, 87];
echo "平均: " . Calculator::average($data) . PHP_EOL;
echo "中位数: " . Calculator::median($data) . PHP_EOL;
echo "标准差: " . Calculator::standardDeviation($data) . PHP_EOL;

注意事项

  • pow()** 运算符功能相同,** 更简洁
  • intdiv() 在 PHP 7+ 中可用,替代整数除法的 floor($a/$b)
  • round() 使用银行家舍入法(四舍六入五成双)

下一节

继续学习:BC Math 任意精度

参考链接