Zend - The PHP Company




Math

Add Code


PI Search  

Type: code fragment
Added by: darkelder
Entered: 13/03/2002
Last modified: 03/12/2001
Rating: - (fewer than 3 votes)
Views: 4875
Find the PI value with these routines. Try come closer to 3.14159265358979323846!!!


<?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 / ($x $x);
            
$s += $r;
        }

        return 
sqrt($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 != 0)
                
$up $x 1;
            elseif (
$l == 0)
                
$dw += 2;

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

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


Usage Example


<?PHP
$pisearch 
= new pisearch();
printf("PI of method ONE = %s<br>"$pisearch->one());
printf("PI of method TWO = %s<br>"$pisearch->two());
?>


Rate This Script





Search



This Category All Categories