Formal power series

From Rosetta Code
Revision as of 11:49, 28 March 2008 by rosettacode>Dirkt (Defined task; added Haskell example)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Task
Formal power series
You are encouraged to solve this task according to the task description, using any language you may know.

A power series is an infinite sum of the form

a0 + a1 * x + a2 * x2 + a3 * x3 + ...

The ai are called the coefficients of the series. Such sums can be added, multiplied etc., where the new coefficients of the powers of x are calculated according to the usual rules.

If one is not interested in evaluating such a series for particular values of x, or in other words, if convergence doesn't play a rule, then such a collection of coefficients is called formal power series. It can be treated like a new kind of number.

Task: Implement formal power series as a numeric type. Operations should at least include addition, multiplication, division and additionally non-numeric operations like differentiation and integration (with an integration constant of zero). Take care that your implementation deals with the potentially infinite number of coefficients.

As an example, define the power series of sine and cosine in terms of each other using integration, as in

sinx = ∫ cosx
cosx = 1 - ∫ sinx

Goals: Demonstrate how the language handles new numeric types and delayed (or lazy) evaluation.

Haskell

newtype Series a = S [a] deriving (Eq, Show)

instance Num a => Num (Series a) where
  fromInteger n = S $ fromInteger n : repeat 0
  negate (S fs) = S $ map negate fs
  S fs + S gs   = S $ zipWith (+) fs gs
  S fs - S gs   = S $ zipWith (-) fs gs
  S (f:ft) * S gs@(g:gt) = S $ f*g : ft*gs + map (f*) gt

instance Fractional a => Fractional (Series a) where
  S (f:ft) / S (g:gt) = S qs where qs = f/g : map ((recip g) *) (ft-qs*gt)
  
int (S fs) = S $ 0 : zipWith (/) fs [1..]

diff (S (_:ft)) = S $ zipWith (*) ft [1..]

sinx,cosx :: Series Rational
sinx = int cosx
cosx = 1 - int sinx

Output (with manual interruption):

*Main> sinx
S [0 % 1,1 % 1,0 % 1,(-1) % 6,0 % 1,1 % 120,0 % 1,(-1) % 5040,0 % 1,1 % 362880,Interrupted.
*Main> cosx
S [1 % 1,0 % 1,(-1) % 2,0 % 1,1 % 24,0 % 1,(-1) % 720,0 % 1,1 % 40320,0 % 1,(-1) % 3628800,Interrupted.