Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute a series

Tags:

java

math

series

Assignment: Write a method to compute the following series: m(i) = 1 - (1/2) + (1/3) - (1/4) + (1/5) - ... + ((-1)^(i+1))/i

Write a test program that displays the following code:

i:       m(i):
5        0,78333
10       0,64563
..       ..
45       0,70413
50       0,68324

I've tried for a couple of hours now, and I just can't think of how to solve this. Maybe I'm just stupid haha :)

Here is my code so far:

package computingaseries;

public class ComputingASeries {

    public static void main(String[] args) {

        System.out.println("i\t\tm(i)");
        for (int i = 5; i <= 50; i += 5) {
            System.out.println(i + "\t\t" + m(i));
        }
    }

UPDATED:

    public static double m(int n) {
        double tal = 0;
        double x = 0;

        for (int i = 1; i <= n; i += 1) {
            if (i == 1) {
                x = 1 - ((Math.pow(-1, (i + 1))) / i);
            } else {
                x = ((Math.pow(-1, (i + 1))) / i);
            }
        }
        tal += x;

        return tal;

    }
}

My wrong output:

i       m(i)
5       0.2
10      -0.1
15      0.06666666666666667
20      -0.05
25      0.04
30      -0.03333333333333333
35      0.02857142857142857
40      -0.025
45      0.022222222222222223
50      -0.02
like image 581
Daniel Avatar asked Aug 28 '26 02:08

Daniel


1 Answers

you have to eliminate the "1-" when you define x, i.e. x = ((-1)^(i+1))/i

EDIT

There is no special case for x==1, x is always defined as x=Math.pow(-1,i+1)/i. Note that ((-1)^(1+1))/1 = ((-1)^2)/1 = 1/1 = 1. Also the tal +=x goes in the for-loop.

like image 164
Fortunato Avatar answered Aug 29 '26 15:08

Fortunato



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!