Program to calculate sum of n integers need help
I am writing code to display the output of a sum of this form:
1 + (1/2) + (1/3) + ... + (1/n)
where n = 50,000
When calculating the sum: once it must be summed from left to right and display the output i.e. the value of the sum
then again it must be summed going right to left.
This is to show the difference in the accuracy of the calculation when it is done from L->R and vice-versa.
Here is the code I have written:
Code:
public class AccurateResult
{
public static void main(String[] args)
{
double n = 50000;
double sum = 1 / 50000;
while(n >= 0)
{
sum += (double) ( 1 / (n - 1) );
--n;
break;
}
System.out.println(" The solution from right to left is: " + (double) sum);
n = 0;
sum = 0;
do
{
sum += (double) ( 1 / (n + 1) );
++n;
} while( n <= 50000);
System.out.print(" The solution from left to right is: " + sum);
}
}
I am getting the proper answer for the left to right sum which would be the bottom half of the code but for the top half going right to left I get 2.000044... something like that when it should be 11.3...something
My algorithm for the R -> L sum is not correct.
Because computing that algorithm would lead to (1 / (1-1) ) which = infinity and (1 / (0 -1) ) which would be -1 for the second last and last term when they should be 1/2 and 1 respectively. So can you help me get the right algorithm?
Re: Program to calculate sum of n integers need help
Unless you are compelled to use while loops it might be easier to use a for loop. The first loop would start at 1 and increment to 49999. The next loop would start at 49999 and decrement to 1.
Regards,
Jim
Re: Program to calculate sum of n integers need help
So basically, for Right to Left
for(n = 49999; n<=1 ; --n)
{
sum+= (1 / n)
}
Re: Program to calculate sum of n integers need help
Almost! In this case n >= 1 or n > 0.
Jim
Re: Program to calculate sum of n integers need help
Oh yeha thats what I mean. Thanks.
I just deleted what I had previously written and did the whole thing with the clear mind and it worked at one go. Haha. I think I am suffering from brain drain or something.
Here it is
Code:
public class Accu
{
public static void main(String[] args)
{
double n ;
double sum = 0;
for( n = 50000; n > 0 ; --n)
{
sum += ( 1 / n );
}
System.out.println(" sum from r to l: " + sum);
sum = 0;
for( n = 1 ; n <= 50000; ++n )
{
sum+= (1 / n);
}
System.out.print(" sum from l to r: " + sum);
}
}
Re: Program to calculate sum of n integers need help
Yep! Been there myself. It happens.
Regards,
Jim