3

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?

silkfire
  • 24,585
  • 15
  • 82
  • 105
Kuroki Kaze
  • 8,161
  • 4
  • 36
  • 48

5 Answers5

11

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

soulmerge
  • 73,842
  • 19
  • 118
  • 155
6

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
silkfire
  • 24,585
  • 15
  • 82
  • 105
  • This all makes me sad. The unary operator precedence and the choice of operator, so close to `*` as to be easily typo-ed. – Kzqai Aug 18 '14 at 19:17
4

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)
Gumbo
  • 643,351
  • 109
  • 780
  • 844
  • 2
    And it seems like gmp_pow accepts only positive powers. Of course, we can convert in to 1/gmp_pow('10', '.01') :) – Kuroki Kaze Jul 31 '09 at 09:49
0

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

Rob
  • 2,148
  • 13
  • 17
0

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".

Ali Gajani
  • 14,762
  • 12
  • 59
  • 100