Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop is not running for float values

i have a for loop like below

<?php 

 for($i=0;$i<=10;$i+0.4){

 echo $i."<br>";
 }

 ?>

this code prints the value of i till 9.6 not 10.

why it returns the value of i=10 at last.

like image 820
manishjangir Avatar asked Nov 07 '11 12:11

manishjangir


People also ask

How to run a loop with a float variable?

First we declare the i float variable. We give it an initial value of 1. The f suffix specifies that this value is a literal float value (and not an integer). The second piece of code looks if i is less than or equal to ( <=) 3f. When it is, the loop executes; else the loop ends. The third part has code that runs after each loop cycle.

What type of variable is I in a for loop?

For the loop variable we use a 32-bits floating-point variable: Three things happen inside this for loop. First we declare the i float variable. We give it an initial value of 1. The f suffix specifies that this value is a literal float value (and not an integer).

Why float is not an iterable object?

Usually we run the loop over iterable objects. In each iteration , It returns next value for the sequence. Like list, dict, tuple are iterable object. But float is not iterable object. Its single value element.

Why are my floating point loops not working?

Those loops can also suffer from a condition that uses a floating-point variable with imprecise values. One way to make those floating-point loops behave properly is with an integer counting variable (Stephens, 2014). Compared to floating-point values, integers don’t have rounding errors.


2 Answers

because of representing of float numbers for machines - http://en.wikipedia.org/wiki/Floating_point

I'd recommend to use integer indexes for loops

like image 158
Distdev Avatar answered Sep 30 '22 18:09

Distdev


Use += to increment it, instead of just plus. As it is now, its an infinite loop for me.

Edit: For some reason PHP doesn't work properly with different types in loops.

This below should work

for($i=0;$i<=100;$i+=4){
   echo $i/10."<br>";
 }

Here's the var_dump

int(0)

float(0.4)

float(0.8)

float(1.2)

float(1.6)

int(2)

float(2.4)

float(2.8)

float(3.2)

float(3.6)

int(4)

float(4.4)

float(4.8)

float(5.2)

float(5.6)

int(6)

float(6.4)

float(6.8)

float(7.2)

float(7.6)

int(8)

float(8.4)

float(8.8)

float(9.2)

float(9.6)

int(10)

That's probably the auto-casting PHP is doing that is causing this

like image 20
Mob Avatar answered Sep 30 '22 17:09

Mob