[Edu-sig] Algebra + Python
Kirby Urner
pdx4d@teleport.com
Tue, 1 May 2001 02:11:30 -0700
Could this be extended to a symbolic math implementation? At least,
could you implement compose, add, subtract, multiply, and divide methods
so that
f.compose(g)
f.add(g)
would work?
--
Seth David Schoen <schoen@loyalty.org> | And do not say, I will study when I
Temp. http://www.loyalty.org/~schoen/ | have leisure; for perhaps you will
down: http://www.loyalty.org/ (CAF) | not have leisure. -- Pirke Avot 2:5
============
Sure.
Compose was already implied in Brent's class, since f(10) returns
a number, and therefore so does g(f(10)) and g(f(10)).
Using operator overriding, we can actually use + - and * for
addition, subtraction and multiplication (I haven't done divide):
Definition and Representation:
>>> f = Poly([1,2,3])
>>> f
x**2 + 2*x + 3
>>> g = Poly([2,3,4,5])
>>> g
2*x**3 + 3*x**2 + 4*x + 5
Negation:
>>> -f
-x**2 - 2*x - 3
Subtraction:
>>> f-g
-2*x**3 - 2*x**2 - 2*x - 2
Evaluation:
>>> g(10)
2345
>>> f(10)
123
Composition:
>>> f(g(10))
5503718
>>> g(f(10))
3767618
Multiplication:
>>> f*g
2*x**5 + 7*x**4 + 16*x**3 + 22*x**2 + 22*x + 15
>>> g*f
2*x**5 + 7*x**4 + 16*x**3 + 22*x**2 + 22*x + 15
Evaluation and Multiplication:
>>> x = -1
>>> eval(str(g*f))
4
>>> h=g*f
>>> h(-1)
4
Negation and Multiplication:
>>> -f*g
-2*x**5 - 7*x**4 - 16*x**3 - 22*x**2 - 22*x - 15
Derivative:
>>> h
2*x**5 + 7*x**4 + 16*x**3 + 22*x**2 + 22*x + 15
>>> h.deriv()
10*x**4 + 28*x**3 + 48*x**2 + 44*x + 22
I'm pretty sure all of the above is correct.
I've put the code I have so far at:
http://www.inetarena.com/~pdx4d/ocn/polynomial.py (Python source)
http://www.inetarena.com/~pdx4d/ocn/polynomial.html (colorized HTML)
Maybe we can improve/streamline the implementation somewhat --
and I wouldn't be surprised if someone, somewhere has implemented
something very similar already.
The hardest part was getting the algebraic strings to look pretty.
Kirby