Answer to Question #55251 in Engineering for Jack

Question #55251
I need help with this program in Java
A cancellation error occurs when you are manipulating a very large number with a
very small number. The large number may cancel out the smaller number. For
example, the result of 100000000.0 + 0.000000001 is equal to 100000000.0. To
avoid cancellation errors and obtain more accurate results, carefully select the
order of computation. For example, in computing the following series, you will
obtain more accurate results by computing from right to left rather than from left
to right:
1 + 1/2 + 1/3 + . . . + 1/n
Write a program that compares the results of the summation of the preceding
series, computing from left to right and from right to left with n = 50000.
1
Expert's answer
2015-10-08T02:42:20-0400
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Main {
public static void main(String[] args) {
// initialize n
int n = 50000;

// loop from left to right
double leftToRight = 0;
for (int i = 1; i <= n; i++) {
leftToRight = leftToRight + 1.0 / i;
}

// loop from right to left
double rightToLeft = 0;
for (int i = n; i > 0; i--) {
rightToLeft = rightToLeft + 1.0 / i;
}

// print
System.out.println("Left to right: " + leftToRight);
System.out.println("Right to left: " + rightToLeft);
// this is used to format difference and avoid something like 1.234234234E-14
NumberFormat formatter = new DecimalFormat("#0.00000000000000000000");
System.out.println("Difference: " + formatter.format(rightToLeft - leftToRight));
}
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS