Raising to power in PHP

2019-01-12 07:19发布

问题:

Well, i need to do some calculations in PHP script. And i have one expression that behaves wrong.

echo 10^(-.01);

Outputs 10

echo 1 / (10^(.01));

Outputs 0

echo bcpow('10', '-0.01') . '<br/>';

Outputs 1

echo bcdiv('1', bcpow('10', '0.01'));

Outputs 1.000....

I'm using bcscale(100) for BCMath calculations.

Excel and Wolfram Mathematica give answer ~0,977237.

Any suggestions?

回答1:

The caret is the bit-wise XOR operator in PHP. You need to use pow() for integers.



回答2:

PHP 5.6 finally introduced an innate power operator, notated by a double asterisk (**) - not to be confused with ^, the bitwise XOR operator.

Before 5.6:

$power = pow(2, 3);  // 8

5.6 and above:

$power = 2 ** 3;

An assignment operator is also available:

$power   = 2 ** 2;
$power **=      2;  // 8

Through many discussions and voting, it was decided that the operator would be right-associative (not left) and its operator precedence is above the bitwise not operator (~).

$a = 2 **  3 ** 2;  // 512, not 64 because of right-associativity
$a = 2 ** (3 ** 2); // 512

$b = 5 - 3 ** 3;    // -22 (power calculated before subtraction)

Also, for some reason that does not make much sense to me, the power is calculated before the negating unary operator (-), thus:

$b = -2 ** 2;        // -4, same as writing -(2 ** 2) and not 4


回答3:

The ^ operator is the bitwise XOR operator. You have to use either pow, bcpow or gmp_pow:

var_dump(pow(10, -0.01));  // float(0.977237220956)


回答4:

The bcpow function only supports integer exponents. Try using pow instead.



回答5:

As of 2014, and the PHP 5.6 alpha update, there's a much included feature that I hope makes it to the final release of PHP. It's the ** operator.

So you can do 2 ** 8 will get you 256. PHP Docs say: "A right associative ** operator has been added to support exponentiation".