0

I attempted to create a method which calculates the sum of the values of another method in the same way the capital sigma notation does in math. I wanted it to use successive natural numbers as input variables for the function and use recursion to sum it all up. However, as I wanted to create a method for general summation, I am not sure how to assign another (single variable) method as an input variable.

I thought of something like this:

    public static int sum(int lowerbound, int upperbound, function(int x)){
        int partialsum = 0;
        for (int i = lowerbound; i <= upperbound; i++){
        partialsum = partialsum + function(i);
        }
        return partialsum;
    }

Is it possible?

0

2 Answers 2

3

Yes, it is possible; but you would need to pass a IntFunction (Java is not JavaScript). Like,

public static int sum(int lowerbound, int upperbound, IntFunction<Integer> function) {
    int partialsum = 0;
    for (int i = lowerbound; i <= upperbound; i++) {
        partialsum = partialsum + function.apply(i);
    }
    return partialsum;
}

And then to use it, something like

public static void main(String[] args) {
    System.out.println(sum(1, 10, a -> a));
}

Which outputs

55

It isn't clear what result you would expect (or what function you intended to pass).

Sign up to request clarification or add additional context in comments.

2 Comments

I am new to programming and want to incorporate it into solving my math homework. Right now it's just practice for me. Originally I tried to write a program which approximates the Kempner Series and I then I wanted to sum up some probabilities from Bernoulli trials.
IntUnaryOperator Is probably a better choice
0

You pass in a IntUnaryOperator

public static int sum(int lowerbound, int upperbound, IntUnaryOperator func) { 
    ...
    partialsum += func.applyAsInt(i);

Then, either pass a method in, or use a lambda:

sum(1, 2, n -> n * 2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.