Skip to content

Instantly share code, notes, and snippets.

@crakjie
Created December 19, 2018 09:23
Show Gist options
  • Save crakjie/757ca36e6f91e32a33bbf096175dc45f to your computer and use it in GitHub Desktop.
Save crakjie/757ca36e6f91e32a33bbf096175dc45f to your computer and use it in GitHub Desktop.
Looking for the last point in a continuous function where the predicat "test" is true
import scala.annotation.tailrec
//Looking for the last point in a continuous function where the predicat "test" is true
@tailrec
def dichotomy(lower : Double, upper: Double)( test: Double => Boolean) : Double = {
val gap = (upper-lower)/ 2
val middle = lower + gap
if(gap <= 1)
lower
else if(test(middle)) {
if(middle == lower) //Float or Double precision error
lower
else
dichotomy(middle,upper)(test)
} else {
if(middle == upper) //Float or Double precision error
lower
else
dichotomy(lower,middle)(test)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment