1 package prefuse.util; 2 3 import java.util.Arrays ; 4 5 import prefuse.Constants; 6 7 13 public class MathLib { 14 15 16 public static final double TWO_PI = 2*Math.PI; 17 18 public static final double LOG10 = Math.log(10); 19 20 public static final double LOG2 = Math.log(2); 21 22 private MathLib() { 23 } 25 26 31 public static double log2(double x) { 32 return Math.log(x)/LOG2; 33 } 34 35 40 public static double log10(double x) { 41 return Math.log(x)/LOG10; 42 } 43 44 51 public static double safeLog10(double x) { 52 boolean neg = (x < 0.0); 53 if ( neg ) { x = -x; } 54 if ( x < 10.0 ) { x += (10.0-x) / 10; } 55 x = Math.log(x) / LOG10; 56 57 return neg ? -x : x; 58 } 59 60 67 public static double safeSqrt(double x) { 68 return ( x<0 ? -Math.sqrt(-x) : Math.sqrt(x) ); 69 } 70 71 91 public static double interp(int scale, double val, double dist[]) { 92 switch ( scale ) { 93 case Constants.LINEAR_SCALE: 94 return linearInterp(val, dist[0], dist[dist.length-1]); 95 case Constants.LOG_SCALE: 96 return logInterp(val, dist[0], dist[dist.length-1]); 97 case Constants.SQRT_SCALE: 98 return sqrtInterp(val, dist[0], dist[dist.length-1]); 99 case Constants.QUANTILE_SCALE: 100 return quantile(val, dist); 101 } 102 throw new IllegalArgumentException ("Unrecognized scale value: "+scale); 103 } 104 105 113 public static double linearInterp(double val, double min, double max) { 114 double denominator = (max-min); 115 if ( denominator == 0 ) 116 return 0; 117 return (val-min)/denominator; 118 } 119 120 128 public static double logInterp(double val, double min, double max) { 129 double logMin = safeLog10(min); 130 double denominator = (safeLog10(max)-logMin); 131 if ( denominator == 0 ) 132 return 0; 133 return (safeLog10(val)-logMin) / denominator; 134 } 135 136 144 public static double sqrtInterp(double val, double min, double max) { 145 double sqrtMin = safeSqrt(min); 146 double denominator = (safeSqrt(max)-sqrtMin); 147 if ( denominator == 0 ) 148 return 0; 149 return (safeSqrt(val)-sqrtMin) / denominator; 150 } 151 152 163 public static double[] quantiles(int n, double[] values) { 164 values = (double[])values.clone(); 165 Arrays.sort(values); 166 double[] qtls = new double[n+1]; 167 for ( int i=0; i<=n; ++i ) { 168 qtls[i] = values[((values.length-1)*i)/n]; 169 } 170 return qtls; 171 } 172 173 185 public static double quantile(double val, double[] quantiles) { 186 int x1 = 1; 187 int x2 = quantiles.length; 188 int i = x2 / 2; 189 while (x1 < x2) { 190 if (quantiles[i] == val) { 191 break; 192 } else if (quantiles[i] < val) { 193 x1 = i + 1; 194 } else { 195 x2 = i; 196 } 197 i = x1 + (x2 - x1) / 2; 198 } 199 return ((double)i)/(quantiles.length-1); 200 } 201 202 } | Popular Tags |