math - Incorrect calculation using decimals in php -
i have arrays, holding numbers multiplication quiz. here examples:
if($level==8){ $first=array(13,14,16,17,18,19); $second=array(9,10,11,12,13,14,15,16,17,18,19);} if($level==9){ $first=array(23,19,46,87,98,39); $second=array(19,10,111,112,139,178,145,166,167,185,192);} if($level>9){ $first=array(2.3,1.9,4.6,8.7,9.8,3.9); $second=array(1.9,10,11.1,11.2,13.9,17.8,14.5,16.6,16.7,18.5,19.2);}
these numbers used calculate answers placed on button , user has click on correct answer.
// correct answer $b=rand(0,5); $c=rand(0,10); $f=$first[$b]; $s=$second[$c]; $d=$f*$s; // wrong answer no. 1 $w1a=rand(0,5); $w1b=rand(0,10); $w1c=$first[$w1a]; $w1d=$second[$w1b]; $w1e=$w1c*$w1d; if ($w1e==$d){ wronganswer1(); } // wrong answer no. 2 $w2a=rand(0,5); $w2b=rand(0,10); $w2c=$first[$w2a]; $w2d=$second[$w2b]; $w2e=$w2c*$w2d; if ($w2e==$d){ wronganswer2(); }
there check on receiving page of posting see if user has indeed got correct answer:
$b=$_post["b"]; $c=$_post["c"]; $subby=$_post["sub"]; $d=$c * $b; $score=$_session["score"]; ?> </head> <body> <?php if ($subby==$d){ echo "<script>correct.play()</script>";} else{ echo "<script>wrong.play()</script>"; } ?> <?php if ($subby==$d) { echo "well done!"; $_session["score"]=$_session["score"]+1; echo "<h3>the button pressed said: ".$subby; echo "</h3><br><h2>"; echo $b."x".$c."=".$subby; echo "</h2><br>"; echo "<h3>your streak worth ".$_session["score"]; } else { echo "<h1>no!<br>"; $_session["score"]=0; echo $b."x".$c."=".$d; echo "<br>"; echo "your streak has been reset 0!</h1>"; }
now, when have whole numbers: no problem. decimals causing problem. code telling player correct calculation wrong!
i've spent time echoing out simple decimal multiplications , output correct (so no truncating of decimals or that)...
why inaccuracy?
i'm guessing comparing floating point numbers in same way integers.
it can't possibly work because of nature of floating point numbers.
you can't check equality of floating point values, can ask if absolute difference within tolerance specify. here's pseudo code show mean:
float x = 1.1; float y = 1.2; float tolerance = 1.0e-3; if (abs(x-y) <= tolerance) { // abs() absolute value function print "within tolerance" } else { print "not within tolerance" }
Comments
Post a Comment