I am supposed to write a Java program to sum the following sequence: 1.0/1.0 + 1.0/2.0 + 1.0/3.0…. + 1.0/15,000,000.0 in increasing order and then again in decreasing order starting from 1.0/15,000,000.0 + 1.0/14,999,999 all the way down to 1.0/1.0 using 32 bit floating point. I’m struggling to figure out how to do this, but here is what I have so far (no idea if it will work):
EDIT: Sorry to open this thing back up, but I’m getting a 1.0 for both answers and I’m pretty sure that’s incorrect. Does anyone know what I did wrong?
public class FloatSum {
public static float increasingSum (float numbers1){
float sum1 = 0;
for (int i = 1; i <= 15000000; i++){
sum1 = sum1 + 1/i;
}
return sum1;
}
public static float decreasingSum (float numbers2){
float sum2 = 0;
for (int i = 15000000; i >= 1; i--){
sum2 = sum2 + 1/i;
}
return sum2;
}
public static void main(String[] args) {
float sum1 = 0;
float sum2 = 0;
System.out.println(increasingSum(sum1));
System.out.println(increasingSum(sum2));
}
}
Your logic in the for loop is not correct. Haha, i’m not quite sure what you’re telling it to do but let’s see if we can walk through it….
Forget the rest of the code for now, and focus on what the for loop is doing:
You initialize float variable ‘a’ as 1/x. Set the end value as the length of the array (good). and then you increment variables ‘a’ by 1 and ‘x’ by 1…
Now think of it this way, you initialize ‘a’ as 1/x, making it 1. It runs through the loop with the value a = 1. Then it increments ‘x’ by 1 and increments ‘a’ by 1. Now think hard because this is where your logic is flawed. This DOES in fact make x = 2 now, but you are ALSO making a = 2. ‘x’ and ‘a’ are independent variables. Reread the definition of the for loop and see if you can reconcile what you are attempting to do.
Now, a loop allows you to do iterations. In this case you have 30,000,000 of them (15,000,000 “counting up” and 15,000,000 “counting down”). So let’s make two for loops, each with 15,000,000 iterations
Now, you want to sum together 1.0/1.0 + 1.0/2.0 + … + 1.0/15,000,000.0. Initialize sum1 at 0:
Each iteration you’re going to add 1/i to the sum. Thus your statement inside each for loop will look like
which is the same as
And there you have it. For the first loop, each iteration adds 1/i starting at i = 1 and ending at i = 15,000,000. For the second loop it adds 1/i starting at i = 15,000,000 and stopping at i = 1. Obviously in your case you can replace 15,000,000 with ‘numbers1.length’. Then return sum1 and all your errors will disappear just like that.
note: careful how you constrain the for loop. Make sure it includes the end values. (note the <= 15,000,000 and >= 1 in the two loops) This will not make much a difference in your code and the answer will come out the same, but in the future it will be significant.