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)); } }
Numbers and figures are an essential part of our world, necessary for almost everything we do every day. As important…
APPROVED BY CLIENTS
"assignmentexpert.com" is professional group of people in Math subjects! They did assignments in very high level of mathematical modelling in the best quality. Thanks a lot
Comments
Leave a comment