Skip to content

Instantly share code, notes, and snippets.

@fredyr
Created January 16, 2014 13:19
Show Gist options
  • Save fredyr/8454877 to your computer and use it in GitHub Desktop.
Save fredyr/8454877 to your computer and use it in GitHub Desktop.
f x = (42-x)^2
impr = [(x, f x) | x <- [0, 0.1 ..]]
opt goal = head $ dropWhile (\(x, err) -> err >= goal) impr
@fredyr
Copy link
Author

fredyr commented Jan 16, 2014

(defn f [x] (Math/pow (- 42 x) 2))
(defn impr [] (map #(vector % (f %)) (iterate (partial + 0.1) 0)))
(defn opt [goal]
  (->> (impr)
      (drop-while (fn [[x err]] (<= goal err)))
      (first)))
(opt 0.5)
;; [41.30000000000032 0.48999999999955635]

@fredyr
Copy link
Author

fredyr commented Jan 16, 2014

from itertools import *

def f(x):
    return (42-x)**2

def improve_gen():
    x, err = 0, f(0)
    while True:
        yield x, err
        new_x = x + 0.1
        x, err = new_x, f(new_x)

def opt(goal):
    return dropwhile(lambda (x,err): err >= goal, improve_gen()).next()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment