blaces
blaces

Reputation: 495

Have a better solution for this math computing? (Java)

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?

Upvotes: 2

Views: 219

Answers (3)

rmk
rmk

Reputation: 11

For java calculations, you must use BigDecimal.

Upvotes: 0

Sonkey
Sonkey

Reputation: 21

1st question: Use Math.round(double) function which returns the closest integer of the double.

You can also use Math.floor(double) to get the closest integer that is less than the double or math.ceil(double) which returns the closest integer that is more than the double.

Upvotes: 0

Jason S
Jason S

Reputation: 189686

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))

Upvotes: 6

Related Questions