Remember High-school maths ? there was this greek letter Sigma ( if i remember correctly ) , followed by an algebraic function like f(n) , where n = a to b would be short-formed as a below the sigma , and b sitting on top of it. I want to make a program version of that. I dont want code , just the idea how that can be done. I tried it out using scala , and it works . This is the working scala version :

object MySum {
  /**
   * Summation takes in a function f , that returns a type double
   * we calculate that function with each value from a to b ,
   * increasing 1 at a time
   */
  def Summation(f: Double => Double, a: Double, b: Double): Double = {
    // tailwise recursion
    def tailwiseSummation(accumulator: Double, count: Double): Double = {
      if (count > b) accumulator
      else tailwiseSummation(accumulator + f(count), count + 1)
    }
    // accumulator starts with f(a) , so count starts from a+1 to remove off-by-one error
    tailwiseSummation(f(a), a + 1)
  }

  def Factorial(num: Double): Double = {
    def tailwise(accumulator: Double, deprecator: Double): Double = {
      if (deprecator == 0) accumulator
      else tailwise(accumulator * deprecator, deprecator - 1) // deprecator deprecating 1 unit at a time
    }
    tailwise(1, num)
  }

  def main(args: Array[String]) {
    println(MySum.Summation(Factorial(_), 2, 7));
  }
}

Update : turns out to be simple enough , just need an interface. something like this.

public class Summation {

    public Double calc(int lower, int upper, Function f) {
        double acc = 0;
        while (lower <= upper) {
            acc += f.definition(lower++);
        }
        return acc;
    }

    public static void main(String[] args) {
        Summation sigma = new Summation();

        // implement definition(double) according to your mathematical function
        // this one does a sum of integers
        System.out.println(sigma.calc(1, 19, new Function() {

            @Override
            public double definition(double x) {
                return x; // this can be more complex
            }
        }));
    }
}

Where Function is a basic interface

public interface Function {
    public double definition(double x);
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.