Created
January 12, 2014 16:12
-
-
Save asm89/8386608 to your computer and use it in GitHub Desktop.
"Inside out" approach to sqrt with convergence as described in https://news.ycombinator.com/item?id=7043943
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function _sqrt($n) { | |
$x = 1.0; | |
$y = 0.5 * (1.0 + 1.0/$n); | |
$z = 1e-10; | |
while (abs($x/$y - 1) > $z) { | |
$x = $y; | |
$y = (0.5 * ($y + $n/$y)); | |
} | |
return $y; | |
} | |
function _sqrt2($n) { | |
$pair = head(filter('converged', sliding(sqrtGuesses($n)))); | |
return $pair[0]; | |
} | |
function sqrtGuesses($n) { | |
$y = 1.0; | |
while (true) { | |
$y = (0.5 * ($y + $n/$y)); | |
yield $y; | |
} | |
} | |
function converged(array $pair) { | |
list($x, $y) = $pair; | |
return abs($x/$y - 1) < 1e-10; | |
} | |
$x = _sqrt(3); | |
var_dump($x); | |
$y = _sqrt2(3); | |
var_dump($y); | |
/* | |
* "library functions" | |
*/ | |
function sliding($xs, $n = 2) { | |
$window = []; | |
$i = 1; | |
foreach ($xs as $x) { | |
array_push($window, $x); | |
if ($i < $n) { | |
$i++; | |
continue; | |
} | |
yield $window; | |
array_shift($window); | |
} | |
} | |
function head($xs) { | |
foreach ($xs as $x) { | |
return $x; | |
} | |
throw new RuntimeException('No head in $xs, is it empty?'); | |
} | |
function filter($predicate, $xs) { | |
foreach ($xs as $x) { | |
if ($predicate($x)) { | |
yield $x; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment