time-based point system

Peter Otten __peter__ at web.de
Thu Sep 14 04:27:11 EDT 2006


Jay wrote:

> That function is absolutely no good for this situation.
> 
> 1. Take a small number.
> 5.4348809719085693
> 
> 2. Put it in the function.
> f(5.4348809719085693) = 1/5.4348809719085693
> 
> 3. Get a large number???
> 0.18399666987533483
> 
> That number is even smaller.  I want a large one coming out.

Not satisfied with with the shrink-wrapped functions available at your local
math-mart? Make your own from only a few data points:

from __future__ import division
import bisect

def make_function(*points):
    """Finest built-to-order maths since Archimedes"""
    points = sorted(points)
    xvalues = [p[0] for p in points]

    def f(x):
        i = bisect.bisect(xvalues, x)
        if i == 0:
            i = 1
        if i >= len(xvalues):
            i = len(xvalues) - 1
        x0, y0 = points[i-1]
        x1, y1 = points[i]
        return (y1-y0)/(x1-x0)*(x-x0) + y0
    return f

if __name__ == "__main__":
    f = make_function((0, 100000), (1, 100), (2, 10), (3, 1))
    for i in range(-1, 21):
        x = i / 10
        print x, "-->", f(x)

Peter




More information about the Python-list mailing list