- Home /
Why does the decimal point matter in my for loop?
I had two identical blocks of code (different variable names), one worked, the other not quite. Straightforward for loops, iterating through an array. The 'z' variable is used in calculations within the loop. This loop worked perfectly:
for(var z = 0.0; z < zDim; z++)
While this loop iterated through the array, setting the same value every time.
for(var z = 0; z < zDim; z++)
The only difference is the decimal point. All my other loops seem to work no problem with simple integers. Inside the loops, calculations are made with a mixture of ints and floats. I know my code works, although it would be awesome if somebody could help me understand why.
You might want to post the complete code including how you declared 'zDim'.
Also mixing float and integer calculations can get confusing so I would start there. But indeed you do need to give some more info and code.
Here's the block. zDim and xDim are global, declared as int. density, xOrigin and zOrigin are floats, also global. The rest is as it is.
for(var z = 0.0; z < zDim; z++) {
for(var x = 0.0; x < xDim; x++) {
var xCoord = xOrigin + x / xDim * density;
var zCoord = zOrigin + z / zDim * density;
var yDim = $$anonymous$$athf.PerlinNoise(xCoord, zCoord);
vertexArray[index] += Vector3(0, yDim * scale, 0);
index++;
}
Does mixing int and float screw things up somewhere?
Apologies for the delay, was battling with my triangle array :)
Answer by tanoshimi · Jul 29, 2014 at 05:51 PM
"Does mixing int and float screw things up somewhere" - almost certainly yes, and this is why Javascript's dynamic typecasting is so dangerous. It's pretty unusual for loop iterators to be anything other than ints, so I'd suggest you explicitly declare them as such. i.e.:
for(var z : int = 0; z < zDim; z++)...
If you want to do some floating point calculations based on the value of the iterator, cast it as a (float) inside the loop block:
var zCoord : float = zOrigin + (float)z / zDim * density;
Just tried it as you've typed it here, i get " ';' expected. Insert a semicolon at the end." I'm still a noob, learning all I can. Perhaps I've done something wrong?
It seems like declaring an integer and then casting as a float seems like extra work for the same end. Wouldn't just implicitly declaring z as float be easier? Or would that cause me problems? I assume that the increment would add 1.0 ins$$anonymous$$d of just 1, making float okay for the iterator. Unless that is more taxing (I'm no expert, but I can't imagine it would be much difference).
It's not to do with how "taxing" it is - it's the inherent imprecision of floating point maths: 1.0++ may or may not be equal to 2.0....
Ah floating point maths gets me again! Thank you for your wise words. You have helped a noob take one more step closer to ... non-noobness.
Your answer
![](https://koobas.hobune.stream/wayback/20220613155314im_/https://answers.unity.com/themes/thub/images/avi.jpg)