Why doesn't this work--Extending Python--?

jeremito jeremit0 at gmail.com
Wed Jan 4 14:18:07 EST 2006


I have written a simple C++ program in my efforts to learn how to
extend Python.  It is shown below.  Everything compiles and installs
correctly, but I get strange answers.  I know the function "Pi" is
correct because when I call it from a C++ code it gives the correct
answers.  This is what I get when I run it in Python:

Python 2.3 (#1, Sep 13 2003, 00:49:11)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import Pie
>>> Pie.Pi(100)
4.244022824665725e-314
>>> Pie.Pi(100000)
6.3659915186006512e-314
>>> Pie.Pi(1000000)
6.3659881268399925e-314

Thanks for the help,
Jeremy

      1 /* PiPython.cpp*/

      2 #include<Python.h>

      3
      4 using namespace  std;

      5
      6 double Pi(int Particles)

      7 {

      8     double PiEst = 0.0;

      9     double x,y;

     10     int CircleArea = 0;
     11     for ( int i = 0; i <= Particles; i++)

     12     {
     13         x = (double) rand()/RAND_MAX;

     14         y = (double) rand()/RAND_MAX;

     15

     16         if (sqrt(pow(x,2)+pow(y,2)) <= 1.0)

     17         {

     18             CircleArea++;
     19         }
     20     }

     21     return 4.0*(double(CircleArea)/double(Particles));

     22 }

     23
     24
     25 PyObject *wrap_Pi(PyObject *self, PyObject *args)

     26 {

     27     int Particles;
     28     int Pie;
     29     if (!PyArg_ParseTuple(args, "i", &Particles))

     30         return NULL;

     31     Pie = Pi(Particles);

     32     return Py_BuildValue("d", Pie);
     33 }
     34

     35 /* List of all functions in the module */
     36 static PyMethodDef PieMethods[] =
     37 {
     38     {"Pi", wrap_Pi, METH_VARARGS},
     39     {NULL, NULL}
     40 };
     41
     42 /* Module Initialization function */
     43 PyMODINIT_FUNC initPie(void)
     44 {
     45     Py_InitModule("Pie", PieMethods);
     46 }




More information about the Python-list mailing list