0

I have the following code (where generateGaussian is a function previously defined elsewhere):

function varInstance(stdev, scaling, shift){
gg = -999;
 do {
    gg = generateGaussian(0, stdev);
 }
 while (-3 > gg > 3);
 return ((gg * scaling) + shift);
}

What I want it to do is to produce a value between -3 and +3 But I notice that occasionally it gives me values >3. I have not not noticed it giving me values <-3, though. What am I doing wrong and how can I change it to limit the output to the -3...3 range?

  • 1
    `-3 > gg > 3` is `(-3 > gg) > 3)` which is `(true|false) > 3` which is always false because `false > 3` is `0 > 3` which is false, and `true > 3` is `1 > 3` which is also false. If you want to compare a variable against two values, you have to do so with a logical operator, in this case I'm guessing you want "and": `-3 > gg && gg > 3`. – T.J. Crowder May 12 '22 at 09:37
  • Side note: Your code is falling prey to what I call [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html): You need to declare `gg`. I recommend always using strict mode (by using modules, which are strict by default) so that that's the error it always should have been. :-) Separately, there's no need to give `gg` an initial value (`-999`), since its value isn't tested before a different value is assigned to it in the loop. – T.J. Crowder May 12 '22 at 09:37
  • 2
    **Oops**, my bad, you want "or": `-3 > gg || gg > 3`. I should have read the description more closely. – T.J. Crowder May 12 '22 at 09:42
  • 1
    Many thanks @T.J.Crowder! I am not a JS programmer -- I translated this from Python for a web-based experiment pack. I would have NEVER worked that out. Thanks also for the heads up post he global variable issue! – Marc Buehner May 12 '22 at 10:31

0 Answers0