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.

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

This is caused by the static variable (en.wikipedia.org/wiki/Static_variable) not differences in "execution stack".
Thanks @jonls. Updated accordingly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.