[portland] Using log() programmatically

Robin Dunn robin at alldunn.com
Fri Sep 28 20:47:58 CEST 2007

Rich Shepard wrote:
>    One of our applications uses wxPython as the UI. One of the widgets is a
> drop-down combo box list of scaling factors for variables. The choices in
> that widget are strings, which do not allow for mathematical computation.
>    I've created a dictionary that associates numbers and log functions with
> the appropriate key strings:
> self.scaleDict = {'x 1': 1, 'x 10': 10, 'x 100': 100, 'x 1,000': 1000,
>                        'x 10,000': 10000, 'x log 10': log(), 'x log 2': log(,2),
>                        'x log e': log(e)}
>    What I want to do is look up the selected key for that variable, then
> adjust a numeric value by multiplying, or taking the logarithm, by the value
> of the key. Doing this for the multipliers is easy enough, but I've no idea
> how to use the logs.

Instead of making the dictionary keys a value, you can make it be a 
function, something like this:

def do_times1(val):
	return val
def do_times10(val):
	return val * 10

def do_log10(val):
	return math.log(val)
def do_log2(val):
	return math.log(val, 2)

Then your dictionary would be defined something like this:

self.scaleDict = {'x 1': do_times1,
                   'x 10': do_times10,
                   'x log 10': do_log10,
                   'x log 2': do_log2,

When you look up an item in the dictionary you'll get a reference to the 
function that you can call just a the same as if you had the original 
function name:

	func = self.scaleDict[key]
	newval = func(origval)

Robin Dunn
Software Craftsman
http://wxPython.org  Java give you jitters?  Relax with wxPython!

More information about the Portland mailing list