Would Anonymous Functions Help in Learning Programming/Python?
Ron Adam
rrr at ronadam.com
Sat Sep 22 03:02:57 EDT 2007
Scott David Daniels wrote:
> Cristian wrote:
>> On Sep 21, 3:44 pm, Ron Adam <r... at ronadam.com> wrote:
>>
>>> I think key may be to discuss names and name binding with your friend.
>
> Here's an idea:
>
> import math
>
> def sin_integral(start, finish, dx):
> total = 0.0
> y0 = math.sin(start)
> for n in range(1, 1 + int((finish - start) / float(dx))):
> y1 = math.sin(start + n * dx)
> total += (y0 + y1)
> y0 = y1
> return total / 2. * dx
>
>
> def cos_integral(start, finish, dx):
> total = 0.0
> y0 = math.sin(start)
> for n in range(1, 1 + int((finish - start) / float(dx))):
> y1 = math.cos(start + n * dx)
> total += (y0 + y1)
> y0 = y1
> return total / 2. * dx
>
> generalize and separate the integration technique from the
> function it integrates.
How about this?
It's based on the apple basic program example in How to Enjoy Calculus.
Ron
import math
def integrate(fn, x1, x2, n=100):
# Calculate area of fn using Simpson's rule.
width = float(x2 - x1) / n
area = fn(x1)
if n % 2 != 0: # make sure its even
n += 1
for n in range(1, n):
x = x1 + n * width
if n % 2 == 0:
area += 2.0 * fn(x)
else:
area += 4.0 * fn(x)
area += fn(x2)
return area * (width / 3.0)
def fn(x):
return x**2
print "Area of fn:", integrate(fn, 0, 2)
print "Area of cos fn:", integrate(math.cos, 1, 2)
print "Area of sin fn:", integrate(math.sin, 1, 2)
Area of fn: 2.66666666667
Area of cos fn: 0.0678264420216
Area of sin fn: 0.956449142468
More information about the Python-list
mailing list