OLD | NEW |
| (Empty) |
1 // Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file | |
2 // for details. All rights reserved. Use of this source code is governed by a | |
3 // BSD-style license that can be found in the LICENSE file. | |
4 | |
5 // Various math-related utility functions. | |
6 | |
7 class Math2 { | |
8 /// Computes the geometric mean of a set of numbers. | |
9 /// [minNumber] is optional (defaults to 0.001) anything smaller than this | |
10 /// will be changed to this value, eliminating infinite results. | |
11 static double geometricMean(Array<double> numbers, | |
12 [double minNumber = 0.001]) { | |
13 double log = 0.0; | |
14 int nNumbers = 0; | |
15 for (int i = 0, n = numbers.length; i < n; i++) { | |
16 double number = numbers[i]; | |
17 if (number < minNumber) { | |
18 number = minNumber; | |
19 } | |
20 nNumbers++; | |
21 log += Math.log(number); | |
22 } | |
23 | |
24 return nNumbers > 0 ? Math.pow(Math.E, log / nNumbers) : 0.0; | |
25 } | |
26 | |
27 static int round(double d) { | |
28 return d.round().toInt(); | |
29 } | |
30 | |
31 static int floor(double d) { | |
32 return d.floor().toInt(); | |
33 } | |
34 | |
35 // TODO (olonho): use d.toStringAsFixed(precision) when implemented by DartVM | |
36 static String toStringAsFixed(num d, int precision) { | |
37 String dStr = d.toString(); | |
38 int pos = dStr.indexOf('.', 0); | |
39 int end = pos < 0 ? dStr.length : pos + precision; | |
40 if (precision > 0) { | |
41 end++; | |
42 } | |
43 if (end > dStr.length) { | |
44 end = dStr.length; | |
45 } | |
46 | |
47 return dStr.substring(0, end); | |
48 } | |
49 } | |
OLD | NEW |