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

J

jeremito

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.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 }
 
T

Todd

jeremito said:
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:
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);

Just scanning over this, looks like what you want is double Pie. You
have int. The compiler probably gave a warning.

http://www.signalsguru.net/
 
J

jeremito

Well what do you know, that worked! It's one of those errors that you
can't see yourself, but someone else can see it instantly.
Thanks,
Jeremy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top