PHP Simple Math Calculation - php

can help me to see this calculation? It suppose echo "equal"... but it give me "not equal"
<?php
$tl_pax = 1;
$ct_pax = 2;
$at_pax = 2;
$a = 0.5;
$b = 0.2;
$c = 0.2;
$d = 0.2;
$e = 0.2;
$f = 0.2;
$g = 0.2;
$h = 0.9;
$sum = $a + $b + $c + $d + ($e * $tl_pax) + ($f * $ct_pax) + ($g * $at_pax) + $h;
$total = 3;
if($total == $sum){
echo 'equal: ' . $sum . ' - ' . $total;
}
else{
echo 'not equal: ' . $sum . ' - ' . $total;
}
?>

This is the usual case of the rounding error associated with binary floating point numbers. There are numbers that can't be represented exactly in binary, and thus the result will be of by some margin. To read up on it, the wikipedia article about floating point numbers is great.
The usual pattern found in this case is to pick a delta and compare against it:
if(abs($total - $sum) < 0.01)
echo "equal";
You'll have to pick your delta appropiately according to the usecase.

Check if they have difference less than 0.00001
if(abs($total - $sum) < 0.00001){
http://sandbox.phpcode.eu/g/56905/6
This article shows you why is this happening

It's because your sum is really something like 2.9999999999999999999, due to floating pont arithmetic. PHP just hides that from you when you print it. See the example on floor((0.1+0.7)*10) here: http://php.net/manual/en/language.types.float.php
You should never compare a floating point number for equality. The proper way to compare floats is using a range like:
if($total-0.0000001 <= $sum && $sum <= $total+0.0000001){
You can see it in action here: http://codepad.org/kaVXM5g0
That line just means that $total must be within 0.0000001 of $sum to be considered equal. You can pick the number yourself, depending on the amount of precision you need.
Alternatively you can just round $sum in this case, but then you're basically doing the same thing just with a range from 2.5 - 3.499... instead of 2.9999999 - 3.0000001

The difference is due to the limits of floating point precision.
Values like 0.9 (9/10) can't be written exactly as binary floating point numbers, just like 0.3333... (1/3) can't be written exactly as a decimal fraction. This means that e.g. $h holds an inexact, rounded representation of 0.9. As a result, your calculation yields something very close to 3, but not exactly 3.

Floats are evil.
Quote from http://php.net/float
"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."

Related

Php comparison integer with double

I got a problem with this script
$total = 0;
$expected_total = 1111;
$i = [85.46,85.46,85.46,85.46,85.46,85.46,85.46,85.46,85.46,85.46,85.46,85.46,85.48];
foreach ($i as $item) { $total += $item; }
if($total != $expected_total) {
echo json_encode([$total,$expected_total]);
}
The problem is that at the end of the sum the $total should be equal to the $expected_total.
I thought about different number types, I printed the type of the two vars and I was right, one was double and the other was integer, so I converted the integer to double
$expected_total = 1111.00;
but the result is still the same.
The only solution that I could find was comparing the rappresentation of the two numbers, casting them to a string.
if((string)$total != (string)$expected_total) {
echo json_encode([$total,$expected_total]);
}
But obviously this is kind of a hack.
Have you ever had a similar problem? How have you solved it?
PHP version : 5.5.9
Many Thanks
This is not only PHP problem. It is about representation of floating point numbers in memory. Floating numbers has limited precision. PHP uses IEEE 754. Read carefully the manual page and you will understand.
You can find in manual code snippet of how to do it.
$a = 1.23456789;
$b = 1.23456780;
$epsilon = 0.00001; //very small number
if(abs($a-$b) < $epsilon) {
echo "true";
}
If you want to check them as integers you could round both values.
You should change the if-statement to the following:
if(round($total) != round($expected_total)) {
echo json_encode([$total,$expected_total]);
}
If you do it like this you will compare the rounded values, which will be the same.
There is a big red label in the PHP Manual, that says:
Floating point numbers have limited precision…
So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.
In this specific case, you could add the floating numbers using bcadd() and compare the totals using bccomp(). Both functions are provided by the BC Math extension:
foreach ($i as $item) {
$total = bcadd((string) $total, (string) $item, 2);
}
if (bccomp((string) $total, (string) $expected_total, 2) == 0) {
echo json_encode([$total,$expected_total]);
}

Incorrect results obtained in simple arithmetic using php

Here is a simple PHP script:
<?php
$a = 100;
$b = 91.51;
$c = 8.49;
$d = $a - $b - $c;
echo $d;
?>
It outputs -5.3290705182008E-15 which is ugly
With minor change as follows:
$d = $a - ($b + $c);
echo $d;
?>
The output is 0 which is correct. Why is this happening?
Floating point maths is actually very inaccurate. It's a "best guess" value ;)
In floating point (single precision) 100 - 91.51 is not 8.49 as you would expect, but 8.4899978638 since the value 8.49 cannot be exactly expressed in floating point. With double precision it gets better, as it equates to 8.48999999999999488409 which is a little closer. Still not exact though.
Take the following code example:
echo (100 - 91.51) . "\n";
echo number_format(100 - 91.51, 20) . "\n";
The output of that you would expect to be
8.49
8.49000000000000000000
But in fact it is:
8.49
8.48999999999999488409
It defaults to rounding to 2 decimal places for printing floating point values.
Floating point is very much a trade-off. It is a numerical representation system that provides increased resolution and range at the cost of accuracy. For accuracy, but with limited resolution and range, fixed point arithmetic is often used. For instance, if you were storing voltage values between 0V and 5V and you wanted precise measurements at 1µV resolution (i.e., 0.000001V divisions) you may choose to instead represent your voltages in microvolts not volts, so a value of 100000 would actually be 0.1V, and 3827498 would be 3.827498 volts. The mathematics at your prescribed resolution become precise, however you lack the ability to then represent 287x1036V without having massive variables to store the value.
Try to use number_format like this:
$a = 100;
$b = number_format(91.51, 0, ".", "." );
$c = number_format(8.49, 0, ".", "." );
$d = $a - $b - $c;
echo $d;

Determine if $x is divisible evenly by $y in PHP

I simply want to know if $x is evenly divisible by $y. For example's sake assume:
$x = 70;
$y = .1;
First thing I tried is:
$x % $y
This seems to work when both numbers are integers but fails if they are not and if $y is a decimal less than 1 returns a "Division by zero" error, so then I tried:
fmod($x,$y)
Which returns equally confusing results, "0.099999999999996".
php.net states fmod():
Returns the floating point remainder of dividing the dividend (x) by the divisor (y)
Well according to my calculator 70 / .1 = 700. Which means the remainder is 0. Can someone please explain what I'm doing wrong?
One solution would be doing a normal division and then comparing the value to the next integer. If the result is that integer or very near to that integer the result is evenly divisible:
$x = 70;
$y = .1;
$evenlyDivisable = abs(($x / $y) - round($x / $y, 0)) < 0.0001;
This subtracts both numbers and checks that the absolute difference is smaller than a certain rounding error. This is the usual way to compare floating point numbers, as depending on how you got a float the representation may vary:
php> 0.1 + 0.1 + 0.1 == 0.3
bool(false)
php> serialize(.3)
'd:0.29999999999999999;'
php> serialize(0.1 + 0.1 + 0.1)
'd:0.30000000000000004;'
See this demo:
php> $x = 10;
int(10)
php> $y = .1;
double(0.1)
php> abs(($x / $y) - round($x / $y, 0)) < 0.0001;
bool(true)
php> $y = .15;
double(0.15)
php> abs(($x / $y) - round($x / $y, 0)) < 0.0001;
bool(false)
.1 doesn't have an exact representation in binary floating point, which is what causes your incorrect result. You could multiply them by a large enough power of 10 so they are integers, then use %, then convert back. This relies on them not being different by a big enough factor that multiplying by the power of 10 causes one of them to overflow/lose precision. Like so:
$x = 70;
$y = .1;
$factor = 1.0;
while($y*$factor != (int)($y*$factor)){$factor*=10;}
echo ($x*$factor), "\n";
echo ($y*$factor), "\n";
echo (double)(($x*$factor) % ($y*$factor))/$factor;
There is a pure math library in bitbucket : https://bitbucket.org/zdenekdrahos/bn-php
The solution will be then :
php > require_once 'bn-php/autoload.php';
php > $eval = new \BN\Expression\ExpressionEvaluator();
php > $operators = new \BN\Expression\OperatorsFactory();
php > $eval->setOperators($operators->getOperators(array('%')));
php > echo $eval->evaluate('70 % 0.1'); // 0
0.00000000000000000000
tested on php5.3
credits : http://www.php.net/manual/en/function.bcmod.php#111276
Float-point representation varies from machine to machine. Thankfully there are standards. PHP typically uses the IEEE 754 double precision format for floating-point representation which is one of the most common standards. See here for more information on that. With that said take a look at this calculator for a better understanding as to the why. As for the how I like Tim's solution especially if you're dealing with user input.
As you said, using the modulus operator works fine when it's an integer, so why not set it up so that it operates on integers. In my case, I needed to check divisibility by 0.25:
$input = 5.251
$x = round($input, 3); // round in case $input had more decimal places
$y = .25;
$result = ($x * 1000) % ($y * 1000);
In your case:
$input = 70.12
$x = round($input, 2);
$y = .1;
$result = ($x * 100) % ($y * 100);

Convert exponential number to decimal in php

I have a floating point number in exponential format i.e. 4.1595246940817E-17 and I want to convert it into decimal number like 2.99 etc.
Any help will be appreciated.
format_number() sprintf() don't seem to be working for me.
You need a better math extension like BC Math, GMP... to handle the more precise precision.
Limitation of floating number & integer
Using the BC Math library you can bcscale() the numbers to a predetermined decimal, which sets the parameter for future calculations that require arithmetic precision.
bcscale(3);
echo bcdiv('105', '6.55957'); // 16.007
You could remove the decimal point ($x is your number):
$strfloat = strtolower((string)($x));
$nodec = str_replace(".", "", $x);
Then extract the exponential part.
list($num, $exp) = explode("e", $nodec);
$exp = intval($exp);
Then you have the decimal, and the number, so you can format it:
if($exp < 0) return "0." . ("0" * -($exp + 1)) . $num;
if($exp == 0) return (string)$x;
if($exp > 0) return $num . ("0" * $exp);
This doesn't add precision though, just extra zeroes.
Here's a solution using BC Math, as suggested by ajreal and Russell Dias:
$au = 65536;
$auk = bcdiv($au, 1024);
$totalSize = bcdiv(bcmul(49107, $auk), bcpow(1024, 2), 2);
echo $totalSize . "\n";
// echos 2.99

php calculate float

I have a weird math calculation here. I hope someone will explain.
$a = 1.85/100;
$b = 1.5/100;
$c = 1.1/100;
$d = 0.4/100;
$e = 0.4/100;
$f = 0.4/100;
$g = 0.4/100;
$h = $a + $b + $c + $d + $e + $f + $g;
echo $h*100 ."<br>";
$i = $h-$a;
$i = $i-$b;
$i = $i-$c;
$i = $i-$d;
$i = $i-$e;
$i = $i-$f;
$i = $i-$g;
echo $i;
The last $i value should be 0 but it returns 6.93889390391E-18.
You should read this article:
What Every Computer Scientist Should Know About Floating-Point Arithmetic
Floating point arithmetic is not exact. You should expect small errors. The answer is correct to within a small rounding error. If you need to check if a floating point number is zero it is best not to check that it is exactly equal to zero but instead to check if it is sufficiently close to zero.
If you really need exact arithmetic, don't use floating point types. In your example you could multiply all your numbers by 100 and use integer arithmetic to get an exact answer.
any idea to correct my equation to show final result 0.00 ?
Yeah, round($i, 2)
The "discrepancies" are usually so small, that rounding it to 2 decimals will almost always solve the problem.
There is nothing wrong going there, there are simply rounding approximation.
In this very cas you should multiply all your values for 1000 and do a division at the end of the calculation or, better, resort to precise calculation extension

Categories