bcpow
(PHP 4, PHP 5, PHP 7, PHP 8)
bcpow — 任意精度数字的乘方
参数
num
-
string 类型的底数。
exponent
-
string 类型的指数。必须是没有小数部分的值。指数的有效范围取决于平台,但起码支持
-2147483648
到2147483647
的范围。 scale
-
此参数用于设置结果中的小数位数。如果为
null
,则使用 bcscale() 设置的默认小数位数,或者回退到bcmath.scale
INI 指令的值。
返回值
返回字符串类型的结果。
错误/异常
函数在下列情况会抛出 ValueError:
num
或exponent
不是格式正确的 BCMath 数字字符串exponent
有小数部分exponent
或scale
超出有效范围
如果 num
为 0
且 exponent
为负值,则此函数抛出 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
Michael Bailey (jinxidoru at byu dot net) ¶
20 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 Bailey
http://www.jinxidoru.com
thomas at tgohome dot com ¶
15 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));
}
?>