Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Top Posters

Who's Online (3)

Powered by Vanilla. Made with Bootstrap.
arithmetic / geometric series
  • undead
    Posts: 822
    This little program can find the sum of n terms of an arithmetic progression as well as of a geometric progression.

    If you don't know what arithmetic and geometric progressions are visit these links:

    http://en.wikipedia.org/wiki/Geometric_progression
    http://en.wikipedia.org/wiki/Arithmetic_progression

    #!/usr/bin/python

    #a1: initial term of the arithmetic/geometric progression
    #dif: common difference
    #n: number of terms
    #crat: common ratio

    class ArithmeticProgression:
    def __init__(self, a1, n, dif):
    self.a1 = a1
    self.n = n
    self.dif = dif
    def PrintSum(self):
    S = (self.n/2)*(2*self.a1 + (self.n-1)*self.dif)
    # S = n/2 ( 2a1 + (n-1)dif ) or S = n/2 (a1 + an)
    print S

    class GeometricProgression:
    def __init__(self, a1, n, crat):
    self.a1 = a1
    self.n = n
    self.crat = crat
    def PrintSum(self):
    S = self.a1 * ( (self.crat**self.n - 1) / (self.crat - 1) )
    # S = a1 * commonratio**n - 1 / commonratio - 1, commonratio != 1
    print S


    #first argument: initial term
    #sencond argument: number of terms
    #third argument: common difference for the arithmetic progression and common ratio for geometric progression

    sum1 = ArithmeticProgression(1, 100, 1) #1+2+3+...+100
    sum1.PrintSum()
    sum2 = GeometricProgression(1, 7, 3) #1+3+9+27+81+243+729
    sum2.PrintSum()


    enjoy :)
  • Sh3llc0d3
    Posts: 1,910
    My python coding is non-existant but its always nice to see some mathematics :)