scott1328 wrote:SpeedOfSound wrote:heuristic
- Code: Select all
package heur
object session {
def abs(x:Double) = if(x>=0) x else -x //> abs: (x: Double)Double
def count = 0 //> count: => Int
def sqrtIter(guess: Double, x: Double): Double =
if( isGoodEnough(guess, x) ) guess
else sqrtIter( improve( guess, x), x) //> sqrtIter: (guess: Double, x: Double)Double
def isGoodEnough(guess:Double, x: Double) =
abs(guess * guess - x)/x < 0.000001
//> isGoodEnough: (guess: Double, x: Double)Boolean
def improve(guess: Double, x:Double): Double =
(guess + x / guess) / 2 //> improve: (guess: Double, x: Double)Double
def sqrt(x: Double) = sqrtIter(1.0, x) //> sqrt: (x: Double)Double
sqrt(2) //> res0: Double = 1.4142135623746899
sqrt(4) //> res1: Double = 2.0000000929222947
}
Could be adapted to order from a menu.
I would not call that a heuristic, it is an algorithm that applies Newton's method to calculate a square root. In this particular case it doesn't matter what the I initial estimate for the square root is, it will converge very rapidly and could be carried on to arbitrary precision.
I would say Newton's method is itself a heuristic.
As for picking items from a menu. it would serve very poorly for that purpose,
I think it qualifies. The algorithm takes it upon itself to 'go see'. It can be made to go see for any arbitrarily long period of time. It isn't calculating the answer it is applying a rule that gets arbitrarily closer to the answer. Much like I would walk further toward the object to figure it.
Now I did say could be adapted to pick from a menu. good_enough() would be some measure of my emotional reaction to the current selection. A random pick in the menu would start the process. I may back up to a former pick and reconsider by measuring against picks that followed it's original reading. I actually do this when I order at a restaurant. It's an algorithm I am familiar with. I usually end up with prime rib. And then I hate myself.