improve sum() functions in processing.data

This commit is contained in:
Ben Fry
2017-02-18 13:24:23 -05:00
parent d571dd716b
commit f967150430
5 changed files with 81 additions and 16 deletions

View File

@@ -508,6 +508,27 @@ public class IntDict {
}
public int sum() {
long amount = sumLong();
if (amount > Integer.MAX_VALUE) {
throw new RuntimeException("sum() exceeds " + Integer.MAX_VALUE + ", use sumLong()");
}
if (amount < Integer.MIN_VALUE) {
throw new RuntimeException("sum() less than " + Integer.MIN_VALUE + ", use sumLong()");
}
return (int) amount;
}
public long sumLong() {
long sum = 0;
for (int i = 0; i < count; i++) {
sum += values[i];
}
return sum;
}
public int index(String what) {
Integer found = indices.get(what);
return (found == null) ? -1 : found.intValue();
@@ -676,10 +697,7 @@ public class IntDict {
* @return an IntDict with the original keys, mapped to their pct of the total
*/
public FloatDict getPercent() {
double sum = 0;
for (int i = 0; i < count; i++) {
sum += values[i];
}
double sum = sum(); // a little more accuracy
FloatDict outgoing = new FloatDict();
for (int i = 0; i < size(); i++) {
double percent = value(i) / sum;