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.
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)); } }
It’s the most wonderful time of the year! There’ll be much hollying and jollying, but there will also be plenty…
APPROVED BY CLIENTS
Great service I needed help on an assignment and they do a very thorough and solid job on the assignment and they always reply back to questions. I look forward to working with them again in the future.
Comments
Leave a comment