As of PHP 5.6.0alpha2, there is now an exponentiation operator. If this is kept in the final release, it may be worth noting here.
<?php
// These two will be equivalent as of PHP 5.6.0
$x = $y ** 2;
$x = pow($y, 2);
?>
(PHP 4, PHP 5, PHP 7)
pow — 指数表达式
base
The base to use
exp
指数
base
的
exp
次方的幂。
If both arguments are non-negative integers and the result can be represented
as an integer, the result will be returned with integer type,
otherwise it will be returned as a float.
版本 | 说明 |
---|---|
4.2.0 |
如果不能计算幂,将发出一条警告,pow() 将返回 FALSE 。pow() 开始不产生任何的警告。
|
4.0.6 | 如果可能函数现在会返回 integer 的结果,之前 总是返回 float,For older versions, you may receive a bogus result for complex numbers. |
Example #1 pow() 的一些例子
<?php
var_dump(pow(2, 8)); // int(256)
echo pow(-1, 20); // 1
echo pow(0, 0); // 1
echo pow(-1, 5.5); // PHP >4.0.6 NAN
echo pow(-1, 5.5); // PHP <=4.0.6 1.#IND
?>
Note:
本函数会转换所有输入为数字,即使是非标量值,会导致怪异的(weird)结果。
As of PHP 5.6.0alpha2, there is now an exponentiation operator. If this is kept in the final release, it may be worth noting here.
<?php
// These two will be equivalent as of PHP 5.6.0
$x = $y ** 2;
$x = pow($y, 2);
?>
Many notations use "^" as a power operator, but in PHP (and other C-based languages) that is actually the XOR operator. You need to use this 'pow' function, there is no power operator.
i.e. 3^2 means "3 XOR 2" not "3 squared".
It is particular confusing as when doing Pythagoras theorem in a 'closet points' algorithm using "^" you get results that look vaguely correct but with an error.
Note that pow(0, 0) equals to 1 although mathematically this is undefined.