Page 1 of 1

a bug in the sqrt() function.

Posted: Sun Oct 03, 2004 2:14 pm
by Daisy Cutter
I was trying to write a program to solve the discriminant and it was really <span style='color:blue' title='I'm naughty, are you naughty?'>smurf</span> me off because it woudln't work, then when I used pow($d, "1/2"), it did work. here's the old program that for some inexplicable reason works fine until you ask it to describe the discriminant. The part called test is another example of it not working.

Code: Select all

<?php

$b = $_POST['b'];
$pow = pow($_POST['b'], "2");
$a = $_POST['a'];
$c = $_POST['c'];
$d = $pow-(4*$a*$c);
$sqrd = sqrt($d);

//test
if (is_integer($sqrd)) {
echo "IT IS"; }
elseif (!is_integer($sqrd)) {
echo "IT ISNT"; }
else {
echo "error"; }
//end test

echo "<p>";

if ($do == solve) {
	echo "the discriminant is ".$d."<br /><br >The sqare root of the discriminant is: ".$sqrd."<br /><br />the nature of these roots:<br />";
		if ($d == 0) {
			echo "the discriminant is zero, there is one rational solution"; }
		elseif ($d < 0) {
			echo "the discriminant is negative, there are 2 imaginary roots."; }
		elseif ($d > 0) {
			if (is_integer($sqrd)) {
				echo "the discriminate is a perfect square, there are 2 rational solutions."; }
			else{
				echo "the discriminant is not special, that is, it has 2 irrational solutions and is not a perfect square."; } }
		else {
			echo "for some reason your numbers didn't process. if you can figure out why, PLEASE <a href="/url/contact.php">tell me</a>!"; }
} else {
	echo "
	<form id="quadratic" action="".$_SERVER['PHP_CURRENT']."?do=solve" method="POST">
		A: <input type="text" name="a" size="20" /><br />
		B: <input type="text" name="b" size="20" /><br />
		C: <input type="text" name="c" size="20" /><br />
		<input type="submit" value="solve">
	</form>"; }

// all done!
?>

Posted: Sun Oct 03, 2004 3:47 pm
by feyd
first off, sqrt() returns a float. Second, floating point math has an epsilon, as more and more floats are used in a given formula, the epsilon enlarges because of floating point rounding.

Posted: Sun Oct 03, 2004 6:35 pm
by Roja
pow() also has issues on older versions of php. It may or may not be affecting your code.. I cant really tell.

More information on the pow() bug here. (it includes a workaround that you could try to test whether this issue is the root cause).