Skip to content

Instantly share code, notes, and snippets.

@asm89
Created January 12, 2014 16:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asm89/8386608 to your computer and use it in GitHub Desktop.
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
<?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