fredag 15 mars 2013

Pure python sin

Pure python sin up to 6 decimals (nine degree Taylor expansion, no recursion, 11 mult, 1 div)



"""
f(x) = f(x)+f'(x)*x+f''(x)/2!*(x**2)+...

if f(x) = sin(x)

around 0 is
f(x) = sin(0)+cos(0)*x-sin(0)/2*x2-cos(0)/3!*x3+sin(0)/4!*x4+cos(0)/5!*x5+...
 =  x-x**3/6.+x**5/120.+...
"""

# constants
pi = 3.14159265358979
pi2 = pi / 2
k1 = 1. / (2 * 3)
k2 = 1. / (4 * 5)
k3 = 1. / (6 * 7)
k4 = 1. / (8 * 9)

def sin(x):
    s = 1.0
    if x < 0.0:
        s = -s
        x = -x
    if x > pi2:
        n = int(x / pi2)
        x = x - pi2 * float(n)
        if n & 1: x = pi2 - x
        if n & 2: x = -x
    x2 = x * x
    return s*(x*(1.-k1*x2*(1.-k2*x2*(1.-k3*x2*(1.-k4*x2)))))

Inga kommentarer:

Skicka en kommentar