note 48359 deleted from language.operators.arithmetic by hholzgra

From: Date: Thu, 02 Aug 2012 15:02:33 +0000
Subject: note 48359 deleted from language.operators.arithmetic by hholzgra
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-189795@lists.php.net to get a copy of this message
Note Submitter: gilthans at gmail dot com ---- 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 : "")); } ?>

« previous php.notes (#189795) next »