...

View Full Version : Square root script



funnymoney
08-30-2009, 09:31 PM
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
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, 05:14 AM
Babylonian, capable of doubles:


<?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", $dNumber, babylonianSqrt($dNumber));

?>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum