I have a Java program that I must do for homework, and here’s the formula that I must use: picture of formula. Sorry, I am not a native English speaker, and I don’t know the name of this formula.
I’ve written this solution:
/* Check:
* if: j<=3:
*
* 1/1+sqrt2=0,414213562
* 1/sqrt2+sqrt3=0,317837245
* 1/sqrt3+sqrt4=0,267949192
* res= 0,9999999 =~1.0
*/
double sum = 0;
for (int j = 2; j <= 624; j++)
{
sum += 1 / ((Math.sqrt(j) + Math.sqrt(j + 1)));
}
double res = 0;
res = (double)1 / (1 + Math.sqrt(2)) + sum;
System.out.println("Result is: " + res);
I’ve checked the program for j=2 to j=3, and it gave the right result (around 1.0). So I think it is working well. But, when I’ve tried up to j<=624, my result is: 24.000000000000014
1. How can I make the result will be 24.0 and not 24.000000000014 in my program?
2. Is there a better solution / source code for this math formula? What is this formula’s name in english?
Welcome to the world of floating-point computation. Unless you can rewrite your formula using algebra in a way that uses fewer terms or converges more rapidly, you’re out of luck — floating-point computation is never exact and accumulates errors, as you can see from your example.
(a specific hint in this case: your terms are of the form Xk = 1 / (sqrt(k) + sqrt(k+1)). Try multiplying numerator and denominator by sqrt(k+1) – sqrt(k))