Commit c2fb2ce0 by Jim Newton

### updated notes for live coding

parent b951cf43
 import scala.math._ // find a root of the given function within the given range def binSearch(left:Double,right:Double,f:Double=>Double,epsilon:Double):Double = { // assume f(left) <=0 and f(right) >=0 val m = (left + right) / 2 val fm = f(m) if (abs(fm) < epsilon) m else if (fm < 0) binSearch(m,right,f,epsilon) else binSearch(left,m,f,epsilon) } binSearch(-Pi/10, Pi/20, sin, .0001)
 import scala.math._ // find a root of the given function within the given range def binSearch(left:Double,right:Double,f:Double=>Double,epsilon:Double):Option[Double] = { // assume f(left) <=0 and f(right) >=0 def recur(left:Double,right:Double):Double = { val m = (left + right) / 2 val fm = f(m) if (abs(fm) < epsilon) m else if (fm < 0) recur(m, right) else recur(left, m) } if (f(left) <=0 && f(right) >=0) Some(recur(left,right)) else if (f(left) >=0 && f(right) <=0) Some(recur(right,left)) else None } binSearch(-Pi/10, Pi/20, sin, 0.0001) binSearch(-Pi/10, Pi/20, cos, 0.0001) binSearch(-10.0,10.0,x=>10-x*x*x,0.0001)
 import scala.math._ // find a root of the given function within the given range def binSearch(left:Double,right:Double,f:Double=>Double,epsilon:Double,maxDepth:Int):Option[Double] = { def recur(left:Double,right:Double,depth:Int):Option[Double] = { val m = (left + right) / 2 val fm = f(m) if (depth >= maxDepth) None else if (abs(fm) < epsilon) Some(m) else if (fm < 0) recur(m, right,depth+1) else recur(left, m,depth+1) } if (f(left) <=0 && f(right) >=0) recur(left,right,0) else if (f(left) >=0 && f(right) <=0) recur(right,left,0) else None } binSearch(-Pi/10, Pi/20, sin, 0.0001,32) binSearch(-Pi/10, Pi/20, cos, 0.0001,32) binSearch(-10.0,10.0,x=>10-x*x*x,0.0001,32)
 ... ... @@ -45,3 +45,13 @@ for {n <- 0 to 20 s2 = integral(cos,0,x,almostEqual(0.00001)) delta = s1 - s2 } println(s"\$x delta= \$delta") def doubleRange(lower:Double, upper:Double, steps:Int) = { val step = (upper - lower)/steps for { i <- (0 to steps).view x = lower+ i*step } yield x.min(upper) } (for {x <- doubleRange(-Pi, Pi, 21) c = cos(x)} println(s"x=\$x cos(x)=\$c"))
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!