Using Underscore.PHP and Newton's Method to approximate pi

Written by Ben Wendt

Underscore.js has been ported to Underscore.PHP.

For a simple example, let’s using Newton’s method to approximate pi.

$iterations = 20;
$x = 3;

$_ = new __();

$f = function($x) {return 1 + cos($x);};
$g = function($x) {return -sin($x);};
$h = function() {
    global $x;
    global $f;
    global $g;
    $x = $x - $f($x)/$g($x);
};

$j = [];

for ($i = 0; $i < $iterations; $i++) {
    $j[] = $h;
}

$_->each($j, function($k) {$k();});

echo $x;