PhpSnip.com

User Stats

PI Search

Find the PI value with these routines. Try come closer to 3.14159265358979323846!!!

Info

 Download  View Source (print view)
 Rating : 4.7  Views : 1634

Source Code ( 56 lines )

<?PHP
class pisearch
{
    // public vars
    var $max  = 150000;

    function one()
    {
        /* PI Search! - method 1*/
        // In the books: 1+1/4+1/9+1/16+...=(PI^2)/6
        // got from PHP doc -> PI: 3.14159265358979323846

        // How much greater $max will, more exact the value will be


        for ($x = 1; $x <= $this->max; $x++)
        {
            $r = 1 / ($x * $x);
            $s += $r;
        }

        return sqrt(6 * $s);
        //sqrt = x^(1/2)

    }

    function two()
    {
        /* PI Search! - method 2*/
        // In the books: PI /2 = (2/1)*(2/3)*(4/3)*(4/5)*(6/5)(6/7)
        // got from PHP doc -> PI: 3.14159265358979323846

        // How much greater $max will, more exact the value will be

        // SOME values to make for {} work
        $dw   = 1;
        $l    = 1;
        $up   = 2;
        $pi   = 4;
        for ($x = 2; $x <= $this->max; $x++)
        {
            $l++;
            if ($l % 2 != 0)
                $up = $x + 1;
            elseif ($l % 2 == 0)
                $dw += 2;

            $pi = $pi * ($up/$dw);

            if ($l == 4)
                $l = 0;
        }
        return $pi;
    }
}
?>

Search

Subscribe

  Rss Feeds

Sponsors

Advertise