Random functions
Do not import random in Builder. As mentioned in Wakefield's Daily Tips - #19 by wakecarter Builder scripts already contain the line:
from numpy.random import random, randint, normal, shuffle, choice as randchoice
Their usage follows:
a = random() # for a random number 0 <= a < 1
b = randint(i) # for a random integer 0 <= b < i
c = normal(m, s) # for a random sample from a Gaussian distribution of mean m and standard deviation s
shuffle(d) # to shuffle list d
e = randchoice(d) # for a random item from list c
These auto translate to:
a = Math.random();
b = util.randint(i);
c = normal(m, s);
util.shuffle(d);
e = util.randchoice(d);
However, for them all to work online, you need to define a normal function in Before Experiment in a JavaScript (or Both) code component.
function normal(mean=0, stdev=1) {
const u = 1 - Math.random(); // Converting [0,1] to [1,0]
const v = Math.random();
const z = Math.sqrt( -2.0 * Math.log( u ) ) * Math.cos( 2.0 * Math.PI * v );
// Transform to the desired mean and standard deviation:
return z * stdev + mean;
}
This uses the Box-Muller transform and this Python code came from algorithm - JavaScript Math.random Normal distribution (Gaussian bell curve)? - Stack Overflow.
In Python you can add a size parameter to some of these functions to return a list or array of random numbers, but I would advise against using this since it doesn’t translate to PsychoJS.