My Math Forum

My Math Forum (http://mymathforum.com/math-forums.php)
-   Math Software (http://mymathforum.com/math-software/)
-   -   java programming incorrect answer (http://mymathforum.com/math-software/339314-java-programming-incorrect-answer.html)

MathAboveMeth March 3rd, 2017 05:50 AM

java programming incorrect answer
 
i have to write a program that gives the summation of 1/i for any given i. i came up with the following program but for some reason it always provides the answer 1.0, can someone tell me what is wrong here?

import java.util.Scanner;
class Series{
Scanner sc = new Scanner(System.in);
double series(int i){
if (i==1)
return 1;
else
return 1/(i*i) + series(i-1);
}
public void demo(){
int i;
System.out.println("Provide a number to compute the series for");
i = sc.nextInt();
System.out.println("series of " + i + " is " + series(i));
}
public static void main(String[] args) {
new Series().demo();
}
}

Denis March 3rd, 2017 06:33 AM

Quote:

Originally Posted by MathAboveMeth (Post 563420)
i have to write a program that gives the summation of 1/i for any given i.

Huh?
If i = 2, what d'hell is "summed"?
Please provide an example.
Your post is "obscure"...or do I need another coffee? :confused:

Xxmarijnw March 3rd, 2017 06:53 AM

Assuming $\displaystyle i$ is a variable and not the imaginary unit:

$\displaystyle \sum_{i=0}^\infty \frac{\alpha}i = \infty \thinspace \text{if} \thinspace \alpha\ne{0} \thinspace \wedge \thinspace i\ne{0}$

This can be proven with the harmonic series test. So what do you mean exactly? If you mean just $\displaystyle \frac{1}i$ you can use $\displaystyle i^{-1}$

MarkFL March 3rd, 2017 09:25 AM

I believe the OP's program is supposed to find:

$\displaystyle S_i=\sum_{k=1}^{i}\left(\frac{1}{k}\right)$

It looks to me though, the algorithm coded would provide:

$\displaystyle S_i=\sum_{k=1}^{i}\left(\frac{1}{k^2}\right)$

However, I'm not a Java programmer. :D

johng40 March 3rd, 2017 09:46 AM

Your only error is in method series. You said i is an int, so 1/i*i is 0 for any i>1! So just change 1/i*i to 1.0/i*i.

By the way I am surprised that your program runs as given. I thought main had to be within a public class?


All times are GMT -8. The time now is 01:13 AM.

Copyright © 2018 My Math Forum. All rights reserved.