Turning String into Numerical Equation

Artie Gold artiegold at austin.rr.com
Sun Mar 13 01:10:09 EST 2005


Brian Kazian wrote:
> Thanks for the help, I didn't even think of that.
> 
> I'm guessing there's no easy way to handle exponents or logarithmic 
> functions?  I will be running into these two types as well.

Well, consider:

import math
eval("log(pow(x,2)*pow(y,3),2)",{'pow':math.pow,'log':math.log},{'x':1,'y':2})

[No, you wouldn't want to write it that way; it's merely illustrating 
what you can do without doing much.]

HTH,
--ag

[BTW -- cultural question: Do we top-post here?]

> "Artie Gold" <artiegold at austin.rr.com> wrote in message 
> news:39hrh2F61l1n2U1 at individual.net...
> 
>>Brian Kazian wrote:
>>
>>>Here's my problem, and hopefully someone can help me figure out if there 
>>>is a good way to do this.
>>>
>>>I am writing a program that allows the user to enter an equation in a 
>>>text field using pre-existing variables.  They then enter numerical 
>>>values for these variables, or can tell the program to randomize the 
>>>values used within a certain bounds.  My problem is taking in this 
>>>equation they have written in the text field and converting it into an 
>>>equation Python can calculate.
>>>
>>>The only way I know of to do this is by parsing it, which could get 
>>>pretty nasty with all of the different mathematical rules.  Does anyone 
>>>have a better idea than parsing to compute an equation from a string 
>>>representation?
>>>
>>>Thanks so much!
>>>
>>>Brian Kazian
>>
>>eval()
>>
>>See: http://docs.python.org/lib/built-in-funcs.html#l2h-23
>>
>>HTH,
>>--ag
>>
>>-- 
>>Artie Gold -- Austin, Texas
>>http://it-matters.blogspot.com (new post 12/5)
>>http://www.cafepress.com/goldsays 
> 
> 
> 


-- 
Artie Gold -- Austin, Texas
http://it-matters.blogspot.com (new post 12/5)
http://www.cafepress.com/goldsays



More information about the Python-list mailing list