Hi,
I was wondering how to write code that allowed a user to input a mathematical expression for evaluation. For example, I've written a simple method that calculates Riemann sums.

def riemann(hgLoc, a, b, intervals):
	sums = 0.0
	size = float(b - a) / intervals
	for i in range(0, intervals):
		sums = sums + ((i+ hgLoc) * size + a) ** 2 #It's hard coded to f(x) = x ^ 2 right now...
	sums *= size
	return sums

Is there any way for it to do the following?

def riemann(hgLoc, a, b, intervals, USERINPUTEXPRESSION):
	sums = 0.0
	size = float(b - a) / intervals
	for i in range(0, intervals):
		sums = sums + USERINPUTEXPRESSION((i+ hgLoc) * size + a)
	sums *= size
	return sums

(Also is it possible to do this in Java?)
Thanks for any responses.

Recommended Answers

All 2 Replies

Alright I think I found a reasonable way to do this by using strings and eval().

def riemannFunc(hgLoc, a, b, intervals, func):
	sums = 0.0
	size = float(b - a) / intervals
	for i in range(0, intervals):
		x = ((i+ hgLoc) * size + a)
		sums = sums + eval(func)
	sums *= size
	return sums

>>> riemannFunc(1, 0, 10, 100, "x**2")
338.35000000000008

If anyone knows a better way to do this (apart from checking which I'm going to work on checking later) please let me know.

I have not better alternative that only this interactive loop. Remember to mark thread solved if you think it solved.

from math import *
def riemannFunc(hgLoc, a, b, intervals, func):
        sums = 0.0
        size = float(b - a) / intervals
        for i in range(0, intervals):
            x = ((i+ hgLoc) * size + a)
            sums = sums + eval(func)
        sums *= size
        return sums

def evalx(func):
    x=1
    try:
        if func.find('x')!=-1:
            y=eval(func)
            return func
    except NameError,SyntaxError:
        pass
        raise ValueError,"Formula was not containing x or contains other errors."

def interactive():
    print "Give empty line to finish"
    while True:
        try:
            func= raw_input('Give formula containing x: ')
            if not func: break
            func=evalx(func)
            hgLoc=float(raw_input('Give hgLoc: '))
            a=float(raw_input('Give a: '))
            b=float(raw_input('Give b: '))
            intervals=int(raw_input('Give intervals: '))
            print 'Result: ',riemannFunc(hgLoc, a, b, intervals,func)
            print '='*60
        except ValueError as e:
            print e

if __name__=="__main__":
    interactive()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.