a bug in the sqrt() function.

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Daisy Cutter
Forum Commoner
Posts: 75
Joined: Sun Aug 01, 2004 9:51 am

a bug in the sqrt() function.

Post 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!
?>
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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.
Roja
Tutorials Group
Posts: 2692
Joined: Sun Jan 04, 2004 10:30 pm

Post 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).
Post Reply