Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    Regular Coder funnymoney's Avatar
    Join Date
    Aug 2007
    Posts
    364
    Thanks
    17
    Thanked 24 Times in 24 Posts

    Square root script

    If you ever wandered how square root program might look light, like i did, well, this is how i figure it out to be. Someone could look how to make it work with float numbers.

    PHP Code:
    <?php
    function square_root($square) {
        while (
    $i $square) {
            if (
    $i*$i == $square) {
                
    $square_root $i;
            }
            
    $i++;
        }
        
        if (!
    $square_root) {
            
    $square_root "Square root is not int";
        }
        return 
    $square_root;
    }

    print 
    square_root(49);
    ?>

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Babylonian, capable of doubles:
    PHP Code:
    <?php

    function babylonianSqrt($x$dPrecision 0.0000001)
    {
        if (
    $x 0)
        {
            throw new 
    InvalidArgumentException('Number must be positive!');
        }
        
    $dGuess 1;
        
    $bKeepGoing true;
        while (
    $bKeepGoing)
        {
            
    $dOldGuess $dGuess;
            
    $dGuess = ($dOldGuess + ($x $dOldGuess)) / 2;
            if (
    abs(($dGuess $dOldGuess) / $dOldGuess) <= $dPrecision)
            {
                
    $bKeepGoing false;
            }
        }
        return 
    $dGuess;
    }

    $dNumber 14.34;
    printf("The babylonianSqrt of %0.5f is %0.5f\n"$dNumberbabylonianSqrt($dNumber));

    ?>
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •