"; } if the variable $max = 6; has the followi...">

PHP for looping weird results

I have this code:

for($i = 1; $i <= $max; $i+=0.1) { echo "$i<br>"; } 

if the variable $max = 6; has the following results: 1, 1.1, 1.2, 1.3 .... 5.8, 5.9, 6 , but when the variable $max = 4 has the following results: 1, 1.1 ... 3.8, 3.9 , but the number 4 is missing.

Please explain this behavior and a possible solution to this.

the results match when I use the condition $i <= $max; or $i < $max;

The error occurs when $max 2, 3 or 4

+4
source share
4 answers

You must set the accuracy when using integers,

like this:

 $e = 0.0001; while($i > 0) { echo($i); $i--; } 
+1
source

From http://php.net/manual/en/language.types.float.php

In addition, rational numbers that are accurately represented as floating point numbers in base 10, such as 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which are used internally, regardless of the size of the mantissa Therefore, they cannot be converted to their internal binary copies without a slight loss of accuracy.

To overcome this, you can multiply your numbers by 10. Thus, $max is 40 or 60.

 for($i = 10; $i <= $max; $i+=1) { echo ($i/10).'<br>'; } 
+4
source
  You can use of number_format() <?php $max=6; for($i = 1; number_format($i,2) < number_format($max,2); $i+=0.1) { echo $i."<br>"; } 

? >

+3
source
 $err = .000001//allowable error for($i = 1; $i <= $max+$err; $i+=0.1) { echo "$i<br>"; } 
+2
source

Source: https://habr.com/ru/post/1488846/


All Articles