Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP multiple value for loop [duplicate]

Tags:

php

for-loop

I have the following php for loop

$screen = 1.3; // it can be other decimal value
    for ($i = 1, $k = 0; $i <= $screen; $i += 0.1, $k+=25) {
    echo $i . ' - ' . $k . '<br>';
}

It works fine but i would like to run the for loop til 1.3 - 75 now it print me 1.2 - 50. I try to change $i <= $screen to $i = $screen but it does not work.

like image 303
Zsolt Janes Avatar asked Oct 20 '16 11:10

Zsolt Janes


2 Answers

If you read http://php.net/manual/en/language.types.float.php there's a nice statement you should keep in mind:

Testing floating point values for equality is problematic, due to the way that they are represented internally

To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.

Based on the recommendation there you need to do something like :

<?php
$screen = 1.3; // it can be other decimal value
$epsilon=0.0001;
for ($i = 1, $k = 0; $i <= $screen+$epsilon; $i += 0.1, $k+=25) {
    echo $i . ' - ' . $k . "\n";
}
like image 77
apokryfos Avatar answered Oct 07 '22 20:10

apokryfos


Two solutions:

$screen = 1.4; // it can be other decimal value
    for ($i = 1, $k = 0; $i <= $screen; $i += 0.1, $k+=25) {
    echo $i . ' - ' . $k . '<br>';
}

OR:

$screen = 1.3; // it can be other decimal value
    for ($i = 1, $k = 0; $i <= $screen+0.1; $i += 0.1, $k+=25) {
    echo $i . ' - ' . $k . '<br>';
}

Tested. Both work... as far i have understand what you want to do.

Tested Output of both:

1 - 0
1.1 - 25
1.2 - 50
1.3 - 75
like image 43
Twinfriends Avatar answered Oct 07 '22 21:10

Twinfriends