[Tutor] Advise...
Tony Meyer
tameyer at ihug.co.nz
Wed Jan 26 06:14:33 CET 2005
[Tony Meyer]
> 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).
I should have included some code that does this:
"""
from __future__ import division
import psyco
psyco.full()
fofx = raw_input("What is the function? ")
minimum = raw_input("What is the minimum? ")
maximum = raw_input("What is the maximum? ")
start = time.time()
minimum = float(minimum)
maximum = float(maximum)
total = 0
step = 100000
x = minimum
a = compile(fofx, '<string>', 'eval')
while minimum <= x <= maximum:
area = eval(a)/step
total = total+area
x = x+1/step
print total
"""
This takes ~1.7 seconds here, so about 8 times faster than without the
compile() call, but about 2.5 times slower than directly with the 3*x*x.
=Tony.Meyer
More information about the Tutor
mailing list