Common Math Problems |
| Written by phpecho.com | |||
Any application or program finally does some operations on the inputs provided. The input could be provided by the user or the application itself. More often than not, there could be mathematical operations involved in the program. Mathematical operations bring with them a unique set of problems. We look at a couple of common math ‘gotchas’ in PHP. You do not need to wait for your program to fail before you correct these. You can check for these whenever you do any mathematical operations in your programs.
This is one of the ‘silliest’ errors you will get while working with numbers. But this kind of error becomes silly only when you have identified the issue! As you would have studied in high school, you cannot divide a number by zero. PHP throws a warning if you try the operation. The following code is an example of this type of issue.
<?php
$num = 10;
$den = 0;
echo ("The value when dividing by zero is - ".$num/$den);
?>
The value when dividing by zero is – Note that even though the program has executed, there is no value for the mathematical operator. That is not surprising though! You can eliminate this issue by ensuring that you do not divide using 0. If the denominator is itself calculated during runtime, you may be better off validating to ensure that you do not divide by zero. The example below shows the approach: <?php
$num = 10;
$den = 0;
if ($den != 0){
echo ("The value when dividing by zero is - ".$num/$den);
} else {
echo ("Some error message here");
}
?>
Nan stands for ‘Not a Number’. It is a peculiar value in that this is treated as a number even though you cannot do the common operations allowed with numbers. When we say not allowed, we mean that you will not get the expected outputs. NaN will arise when the mathematical function used has gone out of range. For example, if you try to find the arccosine of 10, you will end up with NaN. When you perform any operation with NaN (for example, adding a non-NaN value with NaN), then the result is always NaN. Another peculiar thing about this value is that it is not equal to itself. Yes, you read that right. If you compare NaN with NaN, the result will be false. If you can take care of the above mentioned two issues, you can breathe easy because you will not run into mathematical problems in PHP.
|