Search code examples
common-lispsymbolic-mathsymbolic-computation

Common Lisp - symbolic polynomial calculation


I would like to perform some symbolic calculations on lisp. I found useful derivative function and I would like to know how to write simple recursive function to add/substract/etc. polynomials.

Input (e.g.): (addpolynomial '(+ (^ (* 2 x) 5) 3) '(+ (^ (* 3 x) 5) (^ (* 3 x) 2)))

Output: (+ (^ (* 5 x) 5) (^ (* 3 x) 2)) 3)

Do you know how to do this? Or maybe you know other symbolic calculation examples?


Solution

  • When I've dealt with polynomials in Lisp in the past, I've used arrays of numbers (letting the variable be assumed, which means I couldn't trivially have things like "x*x + y", but since I didn't need that...).

    That allows you to represent "2x^5 + 3" as #(3 0 0 0 0 2), finding the factor of x^n by (aref poly n) and other handy operations.

    This also allows you to define addition as simply (map 'vector #'+ ...) (multiplication requires a bit more work).