note 112627 added to function.fmod
| From: | AdrienGibrat | Date: | Fri, 05 Jul 2013 22:33:40 +0000 |
| Subject: | note 112627 added to function.fmod | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-195472@lists.php.net to get a copy of this message | ||
There is an elegant way to do compute gcm :
https://en.wikipedia.org/wiki/Greatest_common_divisor
// Recursive function to compute gcd (euclidian method)
function gcd ($a, $b) {
return $b ? gcd($b, $a % $b) : $a;
}
// Then reduce any list of integer
echo array_reduce(array(42, 56, 28), 'gcd'); // === 14
If you want to work with floating points, use approximation :
function fgcd ($a, $b) {
return $b > .01 ? fgcd($b, fmod($a, $b)) : $a; // using fmod
}
echo array_reduce(array(2.468, 3.7, 6.1699), 'fgcd'); // ~= 1.232
You can use a closure in PHP 5.3 :
$gcd = function ($a, $b) use (&$gcd) { return $b ? $gcd($b, $a % $b) : $a; };
----
Server IP: 69.147.83.199
Probable Submitter: 82.236.19.20
----
Manual Page -- http://php.net/manual/en/function.fmod.php
Edit -- https://master.php.net/note/edit/112627
Del: integrated -- https://master.php.net/note/delete/112627/integrated
Del: useless -- https://master.php.net/note/delete/112627/useless
Del: bad code -- https://master.php.net/note/delete/112627/bad+code
Del: spam -- https://master.php.net/note/delete/112627/spam
Del: non-english -- https://master.php.net/note/delete/112627/non-english
Del: in docs -- https://master.php.net/note/delete/112627/in+docs
Del: other reasons-- https://master.php.net/note/delete/112627
Reject -- https://master.php.net/note/reject/112627
Search -- https://master.php.net/manage/user-notes.php