object HelloWorld { def main(args: Array[String]) { println("Test1!") val precision = 31 val normLat = new BitNormalizedDimension(-90d, 90d, precision) val normLon = new BitNormalizedDimension(-180d, 180d, precision) val lat = 45.354875 val lon = 1.395856 val uLat = normLat.normalize(lat) val uLon = normLon.normalize(lon) println(uLat) println(uLon) println(normLat.denormalize(uLat)) println(normLon.denormalize(uLon)) } class BitNormalizedDimension(val min: Double, val max: Double, precision: Int) { require(precision > 0 && precision < 32, "Precision (bits) must be in [1,31]") // (1L << precision) is equivalent to math.pow(2, precision).toLong private val bins = 1L << precision private val normalizer = bins / (max - min) private val denormalizer = (max - min) / bins val maxIndex: Int = (bins - 1).toInt // note: call .toInt after subtracting 1 to avoid sign issues def normalize(x: Double): Int = if (x >= max) { maxIndex } else { math.floor((x - min) * normalizer).toInt } def denormalize(x: Int): Double = if (x >= maxIndex) { min + (maxIndex + 0.5d) * denormalizer } else { min + (x + 0.5d) * denormalizer } } }
We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy. Accept Learn more