# precision - Best way to calculate machine epsilon in PHP?

Get the solution ↓↓↓What is best / most correct way of **directly calculating** machine epsilon (floating point rounding error) in PHP, not using built-in constant`PHP_FLOAT_EPSILON`

? Currently, I've managed to research two ways, "standard" and asymptotically approaching epsilon :

```
// Standard way
$x=1.0;
$dx=2.0;
while (($x/=$dx)+1.0!=1.0);
echo "EPSILON : $x".", DEFINED/CALC : ".round(PHP_FLOAT_EPSILON/$x)."x\n";
// Asymptotically approaching
$x=1.0;
$dx=2.0;
while (($x/=$dx)+1.0!=1.0) $dx/=1.0+10**-5;
echo "EPSILON : $x".", DEFINED/CALC : ".round(PHP_FLOAT_EPSILON/$x)."x\n";
```

The problem is, that they gives answers with different errors :

`EPSILON : 1.1102230246252E-16, DEFINED/CALC : 2x`

`EPSILON : 5.6311222663283E-17, DEFINED/CALC : 4x`

So standard gives Оµ = 1/2Оµ_{0} and other algo gives Оµ = 1/4Оµ_{0}. I'm not sure how epsilon should be calculated right.

### Answer

#### Solution:

Thanks to @EricPostpischil, main cause of error was printing first value of x for which`x+1=1`

and instead of that I should be printing last value of x for which`x+1в‰ 1`

. Fixed code :

```
// Standard way
$x=1.0;
$dx=2.0;
while (true) {
$px = $x;
$x/=$dx;
if ($x+1.0==1.0)
break;
}
printf ("Оµ = $x в‰€ %.1f Оµв‚Ђ \n", $px/PHP_FLOAT_EPSILON);
// Asymptotically approaching
$x=1.0;
$dx=2.0;
while (true) {
$px = $x;
$x/=$dx;
$dx/=1.0+10**-5;
if ($x+1.0==1.0)
break;
}
printf ("Оµ = $x в‰€ %.1f Оµв‚Ђ \n", $px/PHP_FLOAT_EPSILON);
```

Reports =>

Оµ = 1.1102230246252E-16 в‰€ 1.0 Оµв‚Ђ

Оµ = 5.6311222663283E-17 в‰€ 0.5 Оµв‚Ђ

It's good enough now, because first -standard case- reports epsilon to be the same as in PHP documentation.As about second algo, it maybe due to rounding issues and can be interpreted somewhat differently. I.e. if В±Оµ gets you to the next **representable** float number, then representation error is half epsilon, because any change greater than |0.5 Оµв‚Ђ| will be rounded to next representable number. It's similar like physicists counts for measurement errors. Say that you have a ruler with smallest measurement unit of 1 mm. Then adding В±0.5 mm to the current reading and rounding will get you to the next representable reading on the ruler. Thus some says that real measurement error is 0.5 mm, and some that it's 1 mm, depends on definition. Same here.

**Share solution ↓**

### Additional Information:

**Date the issue was resolved:**

Link To Answer People are also looking for solutions of the problem: port 80 in use by "unable to open process" with pid 4!

### Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

### Similar questions

Find the answer in similar questions on our website.

### Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.