Jump to content

PHP math not working correctly...?


Photonic

Recommended Posts

Can someone run this code and tell me why its not giving a difference value of 0 instead of 2.2204460492503E-16 and so on... If you run it you will see that the table shows the values its subtracting, and the difference it gets from them... um .2-.2 = 0...

 

You will notice towards the bottom the values start messing up as well...

 

<table border=0 cellspacing=5 cellpadding=4>
<tr><td>X</td><td>Y</td></tr>
<?php

$x = .3;
$y = .8;
$incrementX = 0;
$incrementY = 0;

function tableData($X,$Y) {
$difference = abs($X - $Y);
echo "<td>Difference: ".$difference."<br>Value: ".$X."</td>";
}

for($loop = 0; $loop != 100; $loop++) {
$incrementX += $x;
$incrementY += $y;

if($incrementX > 1) $incrementX -= 1;
if($incrementY > 1) $incrementY -= 1;

echo "<tr>";
tableData($incrementX,$incrementY);
tableData($incrementY,$incrementX);
echo "</tr>";
}

?>
</table>

Link to comment
https://forums.phpfreaks.com/topic/172790-php-math-not-working-correctly/
Share on other sites

Warning

Floating point precision

It is typical that simple decimal fractions like 0.1 or 0.7 cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9.

 

This is due to the fact that it is impossible to express some fractions in decimal notation with a finite number of digits. For instance, 1/3 in decimal form becomes 0.3.

 

So never trust floating number results to the last digit, and never compare floating point numbers for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

 

 

If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

 

So how can I do this without installing those packages... is it not possible? I suppose I could round the numbers... but it seems like that will eventually get the calculations off.

If the biggest fractions are the fractions of 10, then simply multiply everything by 10 and operate on integers:

 

$x = 3;
$y = 8;
$incrementX = 0;
$incrementY = 0;

/// ...

if($incrementX > 10) $incrementX -= 10;
if($incrementY > 10) $incrementY -= 10;

 

You divide the result by 10 when you are going to display it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.