[Tutor] Advise...
Bill Kranec
billk at fastmail.fm
Wed Jan 26 13:57:33 CET 2005
There has been alot of talk on this list about using list comprehensions
lately, and this could be one of those useful places. While I don't
have time to experiment with real code, I would suggest changing your
function to look like:
steps = [ min_x + i*delta_x for i in range(steps) ]
totalarea = sum([ eval(func_x)*delta_x for x in steps ])
Since list comprehensions are significantly faster than while loops,
this could be a big speed boost.
There may be a mistake or two in the above code, but hopefully the idea
will be helpful.
Bill
TJ wrote:
>> What is the function? 3*x*x
>> What is the minimum? 2
>> What is the maximum? 5
>> 117.000435
>>
>> Which, considering that it is supposed to be exactly 117, It's darn
>> good. Unfortunately, it also takes about
>> 10 seconds to do all that.
>> Any suggestions? Any advice? TIA
>> Jacob Schmidt
>>
>
> Jacob,
>
> You can get better accuracy with orders of magnitude fewer steps by
> evaluating the function at the midpoint of each step rather than the
> low value. This has the added benefit of yielding the same result
> when stepping x up (2 to 5) or down (5 to 2).
>
> Here's some modified code (I don't have psyco):
>
> ########################
> from __future__ import division
> import time
> def reimannSum(func_x, min_x, max_x, steps):
> start = time.time()
> totalArea = 0
> #precalculate step size
> delta_x = 1 / steps
> #set x to midpoint of first step
> x = min_x + delta_x / 2
> while min_x <= x <= max_x:
> totalArea += eval(func_x) * delta_x
> x += delta_x
> return totalArea, steps, time.time() - start
>
> stepsList = [100000, 10000, 1000, 500, 200, 100]
> fmt = 'Area: %f Steps: %d Time: %f'
>
> for steps in stepsList:
> print fmt % reimannSum('3 * x * x', 2, 5, steps)
> ########################
>
>
> The results on my machine are:
>
> Area: 117.000000 Steps: 100000 Time: 44.727405
> Area: 117.000000 Steps: 10000 Time: 4.472391
> Area: 116.999999 Steps: 1000 Time: 0.454841
> Area: 116.999997 Steps: 500 Time: 0.223208
> Area: 116.999981 Steps: 200 Time: 0.089651
> Area: 116.999925 Steps: 100 Time: 0.044431
>
> TJ
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
More information about the Tutor
mailing list