1

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.

wohlstad
  • 12,661
  • 10
  • 26
  • 39

2 Answers2

1

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        # should be the same value you used for c++
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?.

wohlstad
  • 12,661
  • 10
  • 26
  • 39
  • @wohlstad Firstly, thank you. Additionally, in my C++ code, the random generator was of **double** type and gave a sequence of values from 0 to 1, while as per what I could figure **randint** gives an **integer** type. How to cure that since I require decimal values from 0 to 1. – Shakil Imtiaz Dec 08 '22 at 06:21
  • @ShakilImtiaz `rand()` returns an `int`. You convert it to `double` in your code (`(double) rand()/RAND_MAX - 0.5;`) so you can do it similarly in python. – wohlstad Dec 08 '22 at 06:27
  • 1
    you could use this answer: https://stackoverflow.com/questions/6088077/how-to-get-a-random-number-between-a-float-range – PythonTester Dec 08 '22 at 08:52
0

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 = []
Jin Kim
  • 35
  • 1
  • 7