[Edu-sig] More calculus in Python

Kirby Urner urnerk at qwest.net
Tue Dec 28 06:20:44 CET 2004


Note that instead of wrapping my little functions with Function, per
previous post, as of Python 2.4 I have the new decorator syntax with which
to accomplish the same thing:

#--- calc.py

class Function:
    def __init__(self, f):
	self.f = lambda x:  f(x)
    def __add__(self, other):
	return Function(lambda x: self.f(x) + other.f(x))
    def __sub__(self,other):
	return Function(lambda x: self.f(x) - other.f(x))
    def __mul__(self,other):
	return Function(lambda x: self.f(x) * other.f(x))
    def __div__(self,other):
	return Function(lambda x: self.f(x) / other.f(x))
    def __call__(self,x):
	"""call wrapped function with argument x, return result"""
	return self.f(x)

class Pair:
    def __init__(self, u, du):
	self.u  = u
	self.du = du
    def __add__(self, other):
	return Pair(self.u + other.u, self.du + other.du)
    def __sub__(self, other):
	return Pair(self.u - other.u, self.du - other.du)
    def __mul__(self, other):
	return Pair(self.u * other.u, \
                self.du * other.u + self.u * other.du)
    def __div__(self, other):
	return Pair(self.u/other.u, \
                (self.du * other.u - self.u * other.du)/other.u**2)


@Function
def ident(x):  return x

@Function
def one(x):  return 1

p1 = Pair(ident, one)

newp = p1 * p1 * p1

print [newp.u(i)  for i in range(-5,6)]
print [newp.du(i) for i in range(-5,6)]

#---

Testing:

 >>> import calc
 [-125, -64, -27, -8, -1, 0, 1, 8, 27, 64, 125]
 [75, 48, 27, 12, 3, 0, 3, 12, 27, 48, 75]

i.e. I get back the functions u(x) = x**3 and du(x) = 3*x**2, per
differential calculus.

Kirby




More information about the Edu-sig mailing list