Last active
August 29, 2015 14:07
-
-
Save vinhkhuc/0b65b9e493fd07475f45 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.List; | |
/** | |
OUTPUT: | |
+ Sum of 10000 double numbers | |
For the 1st shuffling, sum = 4999499.9999999935 | |
For the 2nd shuffling, sum = 4999499.999999965 | |
+ Sum of 10000 float numbers | |
For the 1st shuffling, sum = 4999512.5 | |
For the 2nd shuffling, sum = 4999498.5 | |
*/ | |
public class SumOfFloatingNumbers { | |
static void testSumOfDoubles(int n) { | |
List<Double> x = new ArrayList<Double>(n); | |
for (int i = 0; i < n; i++) | |
x.add(0.1d * i); | |
// First shuffling | |
Collections.shuffle(x); | |
double res1 = 0d; | |
for (Double e: x) res1 += e; | |
// Second shuffling | |
Collections.shuffle(x); | |
double res2 = 0d; | |
for (Double e: x) res2 += e; | |
System.out.println("+ Sum of " + n + " double numbers"); | |
System.out.println("For the 1st shuffling, sum = " + res1); | |
System.out.println("For the 2nd shuffling, sum = " + res2); | |
} | |
static void testSumOfFloats(int n) { | |
List<Float> x = new ArrayList<Float>(n); | |
for (int i = 0; i < n; i++) | |
x.add(0.1f * i); | |
// First shuffling | |
Collections.shuffle(x); | |
float res1 = 0f; | |
for (Float e: x) res1 += e; | |
// Second shuffling | |
Collections.shuffle(x); | |
float res2 = 0f; | |
for (Float e: x) res2 += e; | |
System.out.println("\n+ Sum of " + n + " float numbers"); | |
System.out.println("For the 1st shuffling, sum = " + res1); | |
System.out.println("For the 2nd shuffling, sum = " + res2); | |
} | |
public static void main(String[] args) throws Exception { | |
testSumOfDoubles(10000); | |
testSumOfFloats(10000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment