0

I'm rewriting a C code to python but it seems I've stuck.

I have the function in C:

  double GetArrival()
  /* ---------------------------------------------
  * generate the next arrival time, with rate 1/2
  * ---------------------------------------------
  */ 
  {
  static double arrival = START;

  SelectStream(0); 
  arrival += Exponential(2.0);
  return (arrival);
  }

This function is called from a main() function. As you can see every time it is called, an exponential random rate of 2.0 is added to arrival. All you have to know is that it's a custom function that returns a random variable.

After consulting ddd on the C file which works as it should, I realized that in the following python "equivalent" the variable arrival gets initialized to START = 0 everytime the function GetArrival() is called. This for some reason doesn't happen in the C, except the first time the function is called.

def GetArrival():
     arrival = START
     SelectStream(0)
     arrival += Exponential(2.0)
     return arrival

So I thought I should omit this evil initialization and that should do it. Did not, because in that case I get the following error:

UnboundLocalError: local variable 'arrival' referenced before assignment

Which kinda makes sense.

So my question is how can I make the python code work like the one in C, without having the variable arrival initialize to zero every time?

Thanks.

milia
  • 521
  • 8
  • 20

1 Answers1

0

This has to do with how python treats the static variable differently from C I think. Try referring to making a static variable in python (static var in function, not class). This stack overflow reference should be of help to you.

Community
  • 1
  • 1
user239546
  • 466
  • 3
  • 7