Home > Mobile >  Translating C to Python: Random number generation (With conditions)
Translating C to Python: Random number generation (With conditions)

Time:12-08

I'm trying to translate a C file to Python and have ran into a small situation. Adding a snippet of the working C code:

int i,j;

double vx[N]; // x velocity array
double vy[N]; // y velocity array

int npart = 7; // 7 points representing the particles are along each direction

/* Initialize the velocities to start the program*/
/* Start with a little random velocity */
for(i=1; i < npart;   i){
    for(j=1; j < npart;   j){
        I = j   (i-1)*(npart-1);
        vx[I] = (double) rand()/RAND_MAX - 0.5;
        vy[I] = (double) rand()/RAND_MAX - 0.5;
    }
}

I can't figure out how to translate the randomising part of the code and translate to python.

This is what I did, (Adding specific snippet)

import numpy as np
import random

npart = 7 #7 points representing the particles are along each direction

for i in range(1, npart):
    for j in range(1, npart):
        I = j   (i - 1)*(npart - 1)
        vx[I] = random() - 0.5
        vy[I] = random() - 0.5

This gives the error:

NameError: name 'vx' is not defined

I'm a student currently learning these, so any help would be very appreciated.
Thanks in advance.

CodePudding user response:

There are 2 issues in your code:

  1. random module usage:
    In order to generate a random integer number the proper way is:
random.randint(from,to)

(random itself is a module, and is not callable via random()).

  1. Lists/Arrays initialization:
    Your lists/arrays are not initialized. You must initialize them with a proper size:
N = 100
vx = [0] * N
vy = [0] * N

Set N to the same value you used in c .
See more info about python arrays: How do I declare an array in Python?.

CodePudding user response:

As the error implies, you did not initialize the vx and vy lists before accessing them. Once you initialize and fill them, you can proceed with the loop.

vx = []
vy = []
  • Related