[Tutor] Advise...
Jacob S.
keridee at jayco.net
Thu Jan 27 02:09:47 CET 2005
Thanks everyone!
Kent started the suggestion of making a code object, but everyone else seems
to have worked their way to it.
Beautiful! I only have to call exec once, and it cuts down time
considerably.
Here is the new code.
Jacob Schmidt
Please remind me if I've forgotten anything.
### Start ###################
from __future__ import division
from math import *
import psyco
psyco.full()
def reimannsum(fofx,x,max1):
total = 0
step = 1e-5
exec "def f(x): return %s" % fofx
while x <= max1:
total = total+f(x)
x = x+step
return abs(total*step)
fofx = raw_input("What is the function? ")
minimum = raw_input("What is the minimum? ")
maximum = raw_input("What is the maximum? ")
minimum = float(minimum)
maximum = float(maximum)
print reimannsum(fofx,minimum,maximum)
#### End ##############################
>> If the user must be able to enter in the function, then it would be
> better
>> to evaluate this once and turn it into some sort of function that
> you can
>> call inside the loop (it's the eval that is so expensive). How to
> do that
>> depends a lot on how complex the possible functions can be (if
> they'll only
>> include 'x*+/-' and numbers, for example, it's not so tricky).
>
> exp = raw_input('Type expression')
> func = eval('lambda x: " + exp)
>
> print func(42)
>
>
> etc...
>
> Or if you really can't grokm lambda:
>
> exec('def func(x): return " + exp)
>
> should do the same...
>
> Alan G.
>
>
>
More information about the Tutor
mailing list