bcpow

(PHP 4, PHP 5, PHP 7, PHP 8)

bcpow任意精度数字的乘方

说明

bcpow(string $num, string $exponent, ?int $scale = null): string

numexponent 次方运算。

参数

num

string 类型的底数。

exponent

string 类型的指数。必须是没有小数部分的值。指数的有效范围取决于平台,但起码支持 -21474836482147483647 的范围。

scale
此参数用于设置结果小数点后的位数。 如果为 null,则默认为使用 bcscale() 设置的默认精度, 或者回退到 bcmath.scale INI 指令的值。

返回值

返回字符串类型的结果。

错误/异常

函数在下列情况会抛出 ValueError

  • numexponent 不是格式正确的 BCMath 数字字符串
  • exponent 有小数部分
  • exponentscale 超出有效范围

如果 num0exponent 为负值,则此函数抛出 DivisionByZeroError 异常。

更新日志

版本 说明
8.4.0 0 的负幂以前返回 0,但现在会引发 DivisionByZeroError 异常。
8.0.0 exponent 有小数部分时,现在会抛出 ValueError 而不是截断。
7.3.0 现在 bcpow() 可以按想要的小数点位数返回数字。 而之前,返回的数字会忽略尾随零(trailing decimal zeroes)。

示例

示例 #1 bcpow() 示例

<?php

echo bcpow('4.2', '3', 2); // 74.08

?>

注释

注意:

PHP 7.3.0 之前,bcpow() 返回的结果,小数点后的小数位数可能比 scale 参数指定的少。只有当结果不需要 scale 允许的所有小数位数时,才会发生这种情况。例如:

示例 #2 bcpow() 小数位数示例

<?php
echo bcpow('5', '2', 2); // 打印 "25" 而不是 "25.00"
?>

参见

  • bcpowmod() - Raise an arbitrary precision number to another, reduced by a specified modulus
  • bcsqrt() - 任意精度数字的二次方根
  • BcMath\Number::pow() - Raises an arbitrary precision number

添加备注

用户贡献的备注 3 notes

up
-1
thomas at tgohome dot com
16 years ago
<?php

bcscale(100);

/*
 * Computes the natural logarithm using a series.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bcln($a, $iter = 10)
{
    $result = "0.0";
    
    for($i = 0; $i < $iter; $i++)
    {
        $pow = (1 + (2 * $i));
        $mul = bcdiv("1.0", $pow);
        $fraction = bcmul($mul, bcpow(bcsub($a, "1.0") / bcadd($a, "1.0"), $pow));
        $result = bcadd($fraction, $result);
    }
    
    return bcmul("2.0", $result);
}

/*
 * Computes the base2 log using baseN log.
 * @note Requires above functions.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bclog2($a, $iter = 10)
{
    return bcdiv(bcln($a, $iter), bcln("2", $iter));
}

/*
 * Computes the base10 log using baseN log.
 * @note Requires above functions.
 * @author Thomas Oldbury.
 * @license Public domain.
 */
function bclog10($a, $iter = 10)
{
    return bcdiv(bcln($a, $iter), bcln("10", $iter));
}


?>
up
-2
Anonymous
20 years ago
Well, if bcpow has limits, then this should work:<?phpfunction bcpow_($num, $power) {    $awnser = "1";    while ($power) {        $awnser = bcmul($awnser, $num, 100);        $power = bcsub($power, "1");    }    return rtrim($awnser, '0.');}?>Just that $power cannot have decimal digits in it.
up
-2
Michael Bailey (jinxidoru at byu dot net)
21 years ago
bcpow() only supports exponents less than or equal to 2^31-1.  Also, bcpow() does not support decimal numbers.  If you have scale set to 0, then the exponent is converted to an interger; otherwise an error is generated.--Michael Baileyhttp://www.jinxidoru.com
To Top