Skip to content

Instantly share code, notes, and snippets.

@non
Last active December 15, 2015 15:58
Show Gist options
  • Select an option

  • Save non/5285241 to your computer and use it in GitHub Desktop.

Select an option

Save non/5285241 to your computer and use it in GitHub Desktop.
import scala.annotation.tailrec
object SnapToReal {
def apply(n: Double, limit: Int = 10, thresh: Double = 0.00000000001): (Double, Int, Int) = {
@tailrec
def outer(i: Int, ex: Int, div: Int): (Double, Int, Int) = {
if (i >= limit) {
(n, 1, 1)
} else if (div < 1) {
outer(i + 1, 1, i + 1)
} else {
val x = math.pow(n * div, ex)
val m = x % 1.0
val d = if (m < 0.5) m else m - 1.0
if (math.abs(d) < thresh) {
(x - m, ex, div)
} else {
outer(i, ex + 1, div - 1)
}
}
}
outer(1, 1, 1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment