473,573 Members | 3,047 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert string to mathematical function

I am extending python with C++ and need some help. I would like to
convert a string to a mathematical function and then make this a C++
function. My C++ code would then refer to this function to calculate
what it needs. For example I want to tell my function to calculate
"x^2 + 3x +2", but later on I may want: "x + 3". Does anybody know how
I can get an arbitrary string in Python (but proper mathematical
function) turned into a C++ function? My one idea (although I don't
know how to implement it, I'm still new at this) is to pass to C++ a
pointer to a (Python) function. Will this work?
Thanks,
Jeremy

Aug 2 '06 #1
5 4425
Em Ter, 2006-08-01 Ã*s 18:45 -0700, jeremito escreveu:
I am extending python with C++ and need some help. I would like to
convert a string to a mathematical function and then make this a C++
function.
I may be wrong, but I don't think you can create new C++ functions
on-the-fly. At least I had the impression that only VMs could do it
(e.g. System.Reflecti on on .NET/Mono world and, of course, Python).
My one idea (although I don't
know how to implement it, I'm still new at this) is to pass to C++ a
pointer to a (Python) function. Will this work?
I think it will, but I can't tell you how =).

--
Felipe.

Aug 2 '06 #2
jeremito wrote:
I am extending python with C++ and need some help. I would like to
convert a string to a mathematical function and then make this a C++
function. My C++ code would then refer to this function to calculate
what it needs. For example I want to tell my function to calculate
"x^2 + 3x +2", but later on I may want: "x + 3". Does anybody know how
I can get an arbitrary string in Python (but proper mathematical
function) turned into a C++ function? My one idea (although I don't
know how to implement it, I'm still new at this) is to pass to C++ a
pointer to a (Python) function. Will this work?
It won't "work" in the sense "you can treat that pointer exactly like a
pointer to a C++ function". You would need to embed Python in your C++
code -- read the "embedding" section of the "extending and embedding"
manual.

So far all we know is that you want Python to call C++ to call Python
back again -- the run-time overhead and the sheer pain of getting all
that working correctly are IMHO not worth it. What is the *total*
functionality of your C++ extension? Why C++ and not C? Why C++ and not
Pyrex?

Consider doing the "extension" as a pure Python module -- Python's
built-in eval() function will certainly do the
parse-and-execute-a-formula trick for you. Even if you have extensive
compute-bound requirements, I'd suggest prototyping in Python first.

If the formula is to be executed many times and speed is a concern,
then consider using the compile() built-in to get a code object, and
see whether psyco wiil speed up its execution. I've never tried that
but it should take you much less than an hour of fiddling about to test
the idea yourself.

Hope some of this helps,
John

Aug 2 '06 #3
Jeremy,

Which method of extension are you using? For example you can pass the
function to C++/C directly using weave, without the need to convert to
Python first. Python has a different syntax than C++. Also I assume you
want exponentiation in you example "x^2..." and not 'xor', well, in
Python that would be "x**2" and in C you would have to include math.h
and then do pow(x,2). In other words there is no easy way to map Python
expressions to C++ (if it would be, Python could just all be mapped to
C++ and run at C++ speed!).

Below is my attempt at using weave (I prefer pyrex myself...). Note:
this won't work too fast if your function changes on-the-fly because
each new version will need to be compiled (gcc will be called and so
on...). So it would only pay off if your function gets compiled ones
and then takes a __very__ long time to compute.

Anyway here is my example:
--------------------------------------------------------------------------------------------
>>import weave
includes="" "
.... #include <math.h>
.... """
>>c_code="""
.... return_val=pow( a,N);
.... """
>>a=42
N=42
ans=weave.inl ine(c_code, ['a','N'], support_code=in cludes)
file changed
None
cc1plus: warning: command line option "-Wstrict-prototypes" is valid
for Ada/C/ObjC but not for C++
>>ans
1.5013093754529 656e+68
>>a**N
150130937545296 572356771972164 254457814047970 568738777235893 533016064L
>>#now call the function again. no compilation this time, the result was cached!
ans=weave.inl ine(c_code, ['a','N'], support_code=in cludes)
ans
1.5013093754529 656e+68
----------------------------------------------------------------------------------
Look up weave for Python (it is a part of scipy) for more examples...

Hope this helps,
Nick Vatamaniuc
jeremito wrote:
I am extending python with C++ and need some help. I would like to
convert a string to a mathematical function and then make this a C++
function. My C++ code would then refer to this function to calculate
what it needs. For example I want to tell my function to calculate
"x^2 + 3x +2", but later on I may want: "x + 3". Does anybody know how
I can get an arbitrary string in Python (but proper mathematical
function) turned into a C++ function? My one idea (although I don't
know how to implement it, I'm still new at this) is to pass to C++ a
pointer to a (Python) function. Will this work?
Thanks,
Jeremy
Aug 2 '06 #4
Nick Vatamaniuc wrote:
Jeremy,

Which method of extension are you using? For example you can pass the
function to C++/C directly using weave, without the need to convert to
Python first. Python has a different syntax than C++. Also I assume you
want exponentiation in you example "x^2..." and not 'xor', well, in
Python that would be "x**2" and in C you would have to include math.h
and then do pow(x,2). In other words there is no easy way to map Python
expressions to C++ (if it would be, Python could just all be mapped to
C++ and run at C++ speed!).

Below is my attempt at using weave (I prefer pyrex myself...). Note:
this won't work too fast if your function changes on-the-fly because
each new version will need to be compiled (gcc will be called and so
on...). So it would only pay off if your function gets compiled ones
and then takes a __very__ long time to compute.

Anyway here is my example:
--------------------------------------------------------------------------------------------
>>>import weave
includes=" ""
.... #include <math.h>
.... """
>>>c_code="""
.... return_val=pow( a,N);
.... """
>>>a=42
N=42
ans=weave.in line(c_code, ['a','N'], support_code=in cludes)
file changed
None
cc1plus: warning: command line option "-Wstrict-prototypes" is valid
for Ada/C/ObjC but not for C++
>>>ans
1.5013093754529 656e+68
>>>a**N
150130937545296 572356771972164 254457814047970 568738777235893 533016064L
>>>#now call the function again. no compilation this time, the result was cached!
ans=weave.in line(c_code, ['a','N'], support_code=in cludes)
ans
1.5013093754529 656e+68
----------------------------------------------------------------------------------
Look up weave for Python (it is a part of scipy) for more examples...

Hope this helps,
Nick Vatamaniuc
jeremito wrote:
>I am extending python with C++ and need some help. I would like to
convert a string to a mathematical function and then make this a C++
function. My C++ code would then refer to this function to calculate
what it needs. For example I want to tell my function to calculate
"x^2 + 3x +2", but later on I may want: "x + 3". Does anybody know how
I can get an arbitrary string in Python (but proper mathematical
function) turned into a C++ function? My one idea (although I don't
know how to implement it, I'm still new at this) is to pass to C++ a
pointer to a (Python) function. Will this work?
Thanks,
Jeremy
Jeremy,

I presume that you have considered and rejected use of Python's eval
function.

To this nonC++ user, it seems the simpler way.

A someone else pointed out, you would need to import the math module.

Colin W.

Aug 2 '06 #5
I was unaware of the exec and eval functions in Python. Without trying
them, they seem to be what I want to do. I'll play around with it and
see if I can figure it out. Thanks for the suggestions everyone.
Jeremy

Aug 2 '06 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
89046
by: Jason Chan | last post by:
i want to covert a querystring to float number in asp. what function should i use? i know cint() can convert string to int but how about float?
2
2739
by: Nathan | last post by:
Is there a way to convert a string to a CipherMessage? I am calling a function that decrypts a CipherMessage and returns the value. The only problem is when I want to use an encrypted value stored in a querystring, I can't figure out how to convert it back to a CipherMessage.
3
3324
by: Maileen | last post by:
Hi, How can we convert string^ to String or to LPCWSTR ? thx, Maileen
6
13478
by: Sandy | last post by:
I'm building a SQL String and I want to choose only the records that are part of the current contractID. My Variable Dim contrID = Request.Params("oId" I put it into the SQL String WHERE (JS_CRM.dbo.cntrct_cntct.ContractId = '" & contrID & "') And I get the error message Syntax error converting from a character string to...
3
3440
by: Petr Jakes | last post by:
Hi, I am trying to convert string to the "escaped string". example: from "0xf" I need "\0xf" I am able to do it like: a="0xf" escaped_a=("\%s" % a ).decode("string_escape") But it looks a little bit complicated in this beautiful language to me .....
5
12703
by: XML newbie: Urgent pls help! | last post by:
function to convert string to 1 dimensional array of long in VB.Net
3
7973
by: Ursula | last post by:
Is it possible to convert a string in a file. The problem is this: I have an object string that is a file xml and I want to pass to Deserialize function, but Deserialize function expect an object of FileStream type and the mode access. There is a function Convert.ChangeType(object value, Type conversionType), but I cant write for example:...
12
13523
by: Peter | last post by:
Trying to convert string to byte array. the following code returns byte array of {107, 62, 194, 139, 64} how can I convert this string to a byte array of {107, 62, 139, 65} System.Text.UTF8Encoding str = new System.Text.UTF8Encoding(); string s = new string((char)107, 1); s += new string((char)62, 1);
9
8233
by: engteng | last post by:
How do I convert string to numeric in VB.NET 2003 ? Example convert P50001 to 50001 or 50001P to 50001 but if P is in middle then not convert. Regards, Tee
0
7783
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7701
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8068
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6424
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5600
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5293
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3735
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1307
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1044
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.