note 48359 added to language.operators.arithmetic
| From: | gilthans at gmail dot com | Date: | Mon, 20 Dec 2004 21:13:59 +0000 |
| Subject: | note 48359 added to language.operators.arithmetic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-82096@lists.php.net to get a copy of this message | ||
Me and a few friends were talking about how math works in coding languages, and after a while of
discussion, we started wondering how does the sqrt() function works, and how does the division work,
using only addition, substraction and multiplication (because that could be easily done using only
addition).
I have best knowledge in PHP, so I had my shot at division, and a while of testing proved that my
code works. I'm posting this here for the curious, even though the normal PHP division works 7
times faster, so I think there is some way of making my code more efficient.
divide($x, $y, $a, 0) is similar to number_format($x/$y, $a);, and divide($x, $y, $a, 1) is similar
to Array(floor($x/$y), $x%$y).
<?php
function divide($x, $y, $a=6, $z=false){
// returns $x/$y
$t = '';
if($y == 0)
return 0;
if(($x < 0 ^ $y < 0) && $x != 0)
$t = '-';
$x = abs($x);
$y = abs($y);
$in = 0;
while(($in+1)*$y <= $x)
$in++;
$r = $x-($in*$y);
if($z)
return Array($in, $r);
$d = '';
$c = 0;
while($r != 0 && $c < $a){
list($u, $r) = divide($r*10, $y, $a, 1);
$c++;
if($c >= $a){
$b = divide($r*10, $y, $a, 1);
$u += ($b[0] > 4) ? 1 : 0;
}
$d .= $u;
}
return intval($t.$in.(($d != '') ? ".".$d : ""));
}
?>
----
Manual Page -- http://www.php.net/manual/en/language.operators.arithmetic.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+48359
Delete -- http://master.php.net/manage/user-notes.php?action=delete+48359&report=yes
Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48359&report=yes&reason=bad+code
Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48359&report=yes&reason=spam
Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48359&report=yes&reason=useless+example
Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48359&report=yes&reason=contains+commercial+links
Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48359&report=yes&reason=useless+note
Reject -- http://master.php.net/manage/user-notes.php?action=reject+48359&report=yes
Search -- http://master.php.net/manage/user-notes.php