It appears you have not yet registered with DEVPPL. To register please click here... (it's fast, easy and free!)

Forum

Log In Sponsors
Board index Programming PHP and MySQL Forum

Mathematical operator, unexpected output

Moderator: Malcolm

Mathematical operator, unexpected output

Postby dobby_uk on Sun May 15, 2005 9:39 pm

Hi Guys,

I have just started learning PHP in the last few days so please be gentle!

When using the mathematical operator ^ (exponentiation), I seem to be getting unexpected output. I always thought (if my maths serves me correctly) that zero to the power something is always zero. Here is a looping piece of test code I am having trouble with:

$c = 0;
$tmp = 0;
for ($i=0;$i<12;$i++) {
$tmp = $c;
$c = $c ^ $i;
echo $tmp . ' ^ ' . $i . ' = ' . $c . '<BR>';
}

This produces the following output:

0 ^ 0 = 0
0 ^ 1 = 1
1 ^ 2 = 3
3 ^ 3 = 0
0 ^ 4 = 4
4 ^ 5 = 1
1 ^ 6 = 7
7 ^ 7 = 0
0 ^ 8 = 8
8 ^ 9 = 1
1 ^ 10 = 11
11 ^ 11 = 0

Can anyone please tell me:

1. How this mathematical operator (^) works.
2. Why the output is not what I expected.
3. How do you evaluate exponents in PHP to give the correct output.

Many, thanks in advance.
dobby_uk
 
Posts: 0
Joined: Sun May 15, 2005 9:20 pm

Postby Malcolm on Mon May 16, 2005 12:36 am

Right now your using the bitwise operator.
http://www.php.net/manual/en/language.o ... itwise.php

Basically your getting the difference between the two numbers.

Exponents are like this:
Code: Select all
<?php
for($i=0;$i<10;$i++){
   echo "2 ^ ".$i." = ".bcpow(2, $i)."<br />\n";
}
?>

http://www.php.net/manual/en/function.bcpow.php

Oh, and 0^1 = 0, #^0 = 1

:)
Image
User avatar
Malcolm
100+ Club
 
Posts: 198
Joined: Thu Oct 07, 2004 9:53 pm
Location: Ontario, Canada


Who is online

Users browsing this forum: No registered users and 0 guests