mardi 22 décembre 2015

Why does pyplot.draw() reseed rand() when called via Python's C API?

I have written a small program that produces unexpected behavior.

I am using Python's C API to plot some random data using pyplot's interactive mode (plt.ion()) from my C application. But every time I call plt.draw(), apparantly rand() is reseeded with the same value. Thus, in below example code, every call to rand() produces the same value.

Is this a bug? Is it only on my machine? How can I work around this?

I am pretty sure this worked some time back. I stumbled accross this today, when I tried to compile and run some code I created and successfully tested some years ago (for the code in this answer).

I'm running Fedora 23.

This is the code:

#include <Python.h>
#include <stdlib.h>
#include <stdio.h>

int main () {
  Py_Initialize();
  PyRun_SimpleString("import matplotlib");
  PyRun_SimpleString("print matplotlib.__version__");
  PyRun_SimpleString("from matplotlib import pyplot as plt");
  //PyRun_SimpleString("plt.ion()");
  for (int i = 0; i < 10; i++) {
    // rand() returns always the same value?!
    int x = rand();
    int y = rand();
    printf("%d %d\n", x, y);
    // comment out the following line to "fix" rand() behavior:
    PyRun_SimpleString("plt.draw()");
  }
  Py_Finalize();
  return 0;
}

The output is like this:

$ gcc test.c -I/usr/include/python2.7 -lpython2.7 && ./a.out
1.4.3
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886
1804289383 846930886




Aucun commentaire:

Enregistrer un commentaire