Created
March 25, 2010 02:09
-
-
Save leegao/343083 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
class reflect(object): | |
def __init__(self, fn=None, step = 0.01, start = 0, limit = None, threshold = 10.**(-3), args = []): | |
self.fn = fn | |
self.step = step | |
self.n = start | |
self.limit = limit | |
self.threshold = threshold | |
self.initial = args | |
self.call = True if fn else False | |
def __call__(self, fn=None): | |
def __(fn=fn, once = False, args = []): | |
if once: | |
return fn(*(args+self.initial)) | |
n = self.n | |
closest = (self.limit, fn(self.limit, *self.initial)) if self.limit else (0,0) | |
while n<self.limit or not self.limit: | |
k = fn(n, *self.initial) | |
if abs(k-n) < closest[1]: closest = (n, abs(k-n)) | |
if abs(float(n) -float(k)) < self.threshold: return n | |
n+=self.step | |
return None, closest | |
if self.call: | |
return __(self.fn) | |
return __ | |
@reflect(start=0.01, step=0.00001, limit = 1.1) | |
def sin(n): | |
return math.sin(n*2*math.pi) | |
print sin(), sin(once=True, args=[sin()]) #0.42922 0.430208613409 | |
@reflect(start = 0.01, step = 0.00001, limit = 10, args = [3], threshold = 10.**-5) | |
def parabola(x, a): | |
return a*x*(1-x) | |
print parabola(), parabola(args = [parabola()],once = True) #0.66667 0.6666633333 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment