CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   Post a PHP snippet (http://www.codingforums.com/forumdisplay.php?f=41)
-   -   Square root script (http://www.codingforums.com/showthread.php?t=175826)

funnymoney 08-30-2009 08:31 PM

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);
?>


Fou-Lu 08-31-2009 04:14 AM

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));

?>



All times are GMT +1. The time now is 07:27 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.