stilts77 - 4 months ago 11
PHP Question

# Incorrect calculation using decimals in php

I have some arrays, holding the numbers for a multiplication quiz. Here are some 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 are used to calculate some answers that are placed on a button and the user has to click on the correct answer.

``````// the correct answer
\$b=rand(0,5);
\$c=rand(0,10);
\$f=\$first[\$b];
\$s=\$second[\$c];
\$d=\$f*\$s;
\$w1a=rand(0,5);
\$w1b=rand(0,10);
\$w1c=\$first[\$w1a];
\$w1d=\$second[\$w1b];
\$w1e=\$w1c*\$w1d;
if (\$w1e==\$d){
}
\$w2a=rand(0,5);
\$w2b=rand(0,10);
\$w2c=\$first[\$w2a];
\$w2d=\$second[\$w2b];
\$w2e=\$w2c*\$w2d;
if (\$w2e==\$d){
}
``````

There is a check on the receiving page of the POSTing to see if the user has indeed got the correct answer:

``````\$b=\$_POST["b"];
\$c=\$_POST["c"];
\$subby=\$_POST["sub"];
\$d=\$c * \$b;
\$score=\$_SESSION["score"];
?>
<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 you pressed said: ".\$subby;
echo "</h3><br><h2>";
echo \$b."x".\$c."=".\$subby;
echo "</h2><br>";
echo "<h3>Your streak is worth ".\$_SESSION["score"];

}
else {
echo "<h1>No!<br>";
\$_SESSION["score"]=0;
echo \$b."x".\$c."=".\$d;
echo "<br>";
echo "Your streak has been reset to 0!</h1>";
}
``````

Now, when I have whole numbers: no problem. But the decimals are causing a problem. My code is telling the player that a correct calculation is wrong!

I've spent some time echoing out simple decimal multiplications and the output is correct (so no truncating of decimals or anything like that)...

Why the inaccuracy?

I'm guessing that you are comparing floating point numbers in the same way as integers.

It can't possibly work because of the nature of floating point numbers.

You can't check equality of floating point values, but you can ask if their absolute difference is within a tolerance that you specify. Here's pseudo code to show what I mean:

``````float x = 1.1;
float y = 1.2;
float tolerance = 1.0e-3;
if (abs(x-y) <= tolerance) {  // abs() is an absolute value function
print "within tolerance"
} else {
print "not within tolerance"
}
``````
Source (Stackoverflow)