 # I want a random integer (WITH seed) between 1 and 4, works in PsychoPy, but not PsychoJS (i.e. when uploading on Pavlovia)

At the start of the experiment, I opened a code component in the Builder to start “Before Experiment”. I’ve written this in Python code:

``````import random
from datetime import datetime

random.seed(datetime.now())

group = random.randint(1,4)
``````

I need this variable (\$group) to have a random (integer) number between 1 and 4. Works perfecty in PsychoPy, but it doesn’t translate into JavaScript. It translates into:

``````import * as random from 'random';
import {datetime} from 'datetime';
random.seed(datetime.now());
group = random.randint(1, 4);
``````

Of course, this code isn’t recognized. Now, I understand tihs is a previously known problem here. However, I don’t understand the solution perfectly. I don’t fully understand how to write this code (in JS) so that it uses time (or any other form of) seed for randomizing numbers. I’m worried if I don’t seed the random number generator, that every single participant in the study would get the same “random” number in the 1-4 range.

Can anyone help me translate the above Python code into JavaScript so that it gives a different random number (between 1 and 4) to every participant?

The random number generator is automatically seeded arbitrarily so you won’t gewt the same number each time (offline or online).

My code snippets page has information about seeding, which is useful if you want to replicate the same series of random numbers.

However, for random balanced allocation to groups online, I’d recommend my VESPR Study Portal.

1 Like

Thank you! So, just to be certain I understood, I can get the same result in JavaScript by using this code?

``````group = Math.floor(Math.random() * 10 + 1);
``````

… as a replacement for this entire Python code?

``````import random
from datetime import datetime

random.seed(datetime.now())

group = random.randint(1,4)
``````

That should give you a random group number from 1 to 10 (as opposed to 1 to 3 in your Python code).

1 Like

Oh, right! Thank you! 