Computes the sum of the values in this vector @return the sum of this vector's values
()
| 477 | * @return the sum of this vector's values |
| 478 | */ |
| 479 | public double sum() |
| 480 | { |
| 481 | /* |
| 482 | * Uses Kahan summation algorithm, which is more accurate then |
| 483 | * naively summing the values in floating point. Though it |
| 484 | * does not guarenty the best possible accuracy |
| 485 | * |
| 486 | * See: http://en.wikipedia.org/wiki/Kahan_summation_algorithm |
| 487 | */ |
| 488 | |
| 489 | double sum = 0; |
| 490 | double c = 0; |
| 491 | for(IndexValue iv : this) |
| 492 | { |
| 493 | double d = iv.getValue(); |
| 494 | double y = d - c; |
| 495 | double t = sum+y; |
| 496 | c = (t - sum) - y; |
| 497 | sum = t; |
| 498 | } |
| 499 | |
| 500 | return sum; |
| 501 | } |
| 502 | |
| 503 | /** |
| 504 | * Computes the mean value of all values stored in this vector |