Reputation: 77
I am using Google Apps Scripts Editor in Google Sheets to run some calculations, but I keep running into an error in my for loops.
Below is a truncated version of my function that has all of the calculations removed and just shows the loops with some counting variables. I've reduced all of the loops, except the 2nd, to only loop through one value. The expected number of iterations should be 27, but I was only getting 26 so I decided to capture each iteration in an array and log that array.
function myFunction() {
var timestamp = new Date();
Logger.log(timestamp);
// Define parameter ranges and increments.
var WTmin = 0.3055, WTmax = /*0.3215*/0.3055, WTinc = 0.0010,
FTmin = 0.1370, FTmax = 0.1630, FTinc = 0.0010,
LLmin = 0.0700, LLmax = /*0.1200*/0.0700, LLinc = 0.0010,
HHmin = 0.2050, HHmax = /*0.2450*/0.2050, HHinc = 0.0010,
CBDmin = 0.0650, CBDmax = /*0.1150*/ 0.0650, CBDinc = 0.0010,
count = 0;
var check = [];
// Loop through all of the combinations
for (var WT = WTmin; WT <= WTmax; WT += WTinc) {
for (var FT = FTmin; FT <= FTmax; FT += FTinc) {
for (var LL = LLmin; LL <= LLmax; LL += LLinc) {
for (var HH = HHmin; HH <= HHmax; HH += HHinc) {
for (var CBD = CBDmin; CBD <= CBDmax; CBD += CBDinc) {
count++;
check.push(FT);
}
}
}
}
}
}
The log is below:
[15-09-02 19:20:58:047 PDT] count: 26
[15-09-02 19:28:58:506 PDT] check: [0.137,0.138,0.139,0.14,0.14100000000000001,0.14200000000000002,0.14300000000000002,0.14400000000000002,0.14500000000000002,0.14600000000000002,0.14700000000000002,0.14800000000000002,0.14900000000000002,0.15000000000000002,0.15100000000000002,0.15200000000000002,0.15300000000000002,0.15400000000000003,0.15500000000000003,0.15600000000000003,0.15700000000000003,0.15800000000000003,0.15900000000000003,0.16000000000000003,0.16100000000000003,0.16200000000000003]
For some reason, when the loop is incremented, a tiny fraction is being added on. Thus, my loop only goes through 26 iterations because the additional fraction is triggering the end of my loop. Can someone please explain why this is happens and/or suggest a fix?
Thank you so much!
Upvotes: 0
Views: 135
Reputation: 19834
this is not specific to apps script. its expected in any language that uses floating point (like javascript).
in your case you need to round the values to the wanted decimal digits you want.
Upvotes: 1