Esempio n. 1
0
def secant(y: sympy.core,
           x0: float,
           x1: float,
           epsilon: float = 0.00001,
           maxtime: int = 50) -> (list, list):
    '''
        弦截法, 使用newton 差商计算,每次只需计算一次f(x)
        secant method for finding a zeropoint of a func
        y is the func , x0 is the init x val,     epsilon is the accurrency
    '''
    if epsilon < 0: epsilon = -epsilon
    ct = 0
    x0, x1 = float(x0), float(x1)
    li = [x0, x1]
    t = y.free_symbols
    varsymbol = 'x' if len(t) == 0 else t.pop()
    last = y.subs(varsymbol, x0)
    vals = [last]
    while 1:
        cur = y.subs(varsymbol, x1)
        vals.append(cur)
        x = x1 - cur * (x1 - x0) / (cur - last)
        x0, x1 = x1, x
        last = cur
        li.append(x)
        ct += 1
        if ct > maxtime:
            print(
                "after iteration for {} times, I still havn't reach the accurrency.\
                    Maybe this function havsn't zeropoint\n".format(ct))
            return li, vals
        if abs(x0 - x1) < epsilon: return li, vals
        x0 = x
Esempio n. 2
0
def newton(y: sympy.core,
           x0: float,
           epsilon: float = 0.00001,
           maxtime: int = 50) -> (list, list):
    '''
        newton 's iteration method for finding a zeropoint of a func
        y is the func, x0 is the init x val: int float epsilon is the accurrency
    '''
    if epsilon < 0: epsilon = -epsilon
    ct = 0
    t = y.free_symbols
    varsymbol = 'x' if len(t) == 0 else t.pop()
    x0 = float(x0)
    y_diff = y.diff()
    li = [x0]
    vals = []
    while 1:
        val = y.subs(varsymbol, x0)
        vals.append(val)
        x = x0 - val / y_diff.subs(varsymbol, x0)
        li.append(x)
        ct += 1
        if ct > maxtime:
            print(
                "after iteration for {} times, I still havn't reach the accurrency.\
                    Maybe this function havsn't zeropoint\n".format(ct))
            return li, val
        if abs(x - x0) < epsilon: return li, vals
        x0 = x