Log in

View Full Version : Warning: Division by zero



rhodarose
11-22-2010, 02:23 AM
Good day I got a warning like this :
Warning: Division by zero in C:\Documents and Settings\LT\report.php on line 122

Warning: Division by zero in C:\Documents and Settings\LT\report.php on line 220

I have this code in line 22:


$yield = ($c_output / $f_input) * 100;


and this is my code in line 220


$yield = ($sol_output / $buff_input) * 100;


my c_output is = 65.17
f_input is = 68.40

so the result should be : 95.27 but on my output is 0.00%

and my sol_output = 0.00
buff_input = 0. 00

and the result is 0.00 % which is correct but why I got this warning.


Thank you

jscheuer1
11-22-2010, 02:50 AM
In ordinary math division my 0 is meaningless:

http://en.wikipedia.org/wiki/Division_by_zero

http://www.mathfail.com/divide-by-zero9.jpg

djr33
11-22-2010, 03:23 AM
There are two ways you can approach this:

1. Control the denominator so that it never is 0.
Here are two methods:

<?php $c = $a/(0.0001+$b); ?>
<?php $c = $a/($b==0?0.0001:$b); ?>
The first just adds a very small amount to be sure it's never zero-- this assumes it's an integer or theoretically you could have -.0001 and have the same problem.
The second is an embedded if statement (a ternary operator, to be specific) that replaces a value of 0 with .0001, but otherwise leaves it alone. A little more complex, a little more accurate.
Note that .0001 will be generally a good enough approximation unless you are doing higher level math in which case you probably should approach this another way in general.

2. Check if it's 0 and if so display something else. Simple if statement.

traq
11-22-2010, 04:00 AM
Regarding Daniel's warning about higher-level math and precision:


http://php.net/manual/en/language.types.float.php
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 (http://www.php.net/manual/en/ref.bc.php) and gmp (http://www.php.net/manual/en/ref.gmp.php) functions are available.

About his suggestions for methods: using an if($denominator == 0)-type statement is the best way to go.