[ create a new paste ] login | about

Link: http://codepad.org/vKdq0XlL    [ raw code | output | fork ]

Python, pasted on Oct 11:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def secant(base, exp=2, it=20):
    def f(x):
        return x**exp - base
    eps = 1e-9
    x1 = base / float(exp**2)
    xnm1 = x1 - 5
    xnm2 = x1 + 5
    xn = 0
    for n in range(it):
        if abs(xnm1-xnm2) <= eps: break
        q = (xnm1-xnm2)/(f(xnm1)-f(xnm2))
        xn = xnm1 - (f(xnm1)*q)
        print xnm1, xnm2, q
        xnm1, xnm2 = xn, xnm1
    return xn

print secant(2, 2)


Output:
1
2
3
4
5
6
7
8
9
10
11
12
-4.5 5.5 1.0
-22.75 -4.5 -0.0366972477064
-3.83027522936 -22.75 -0.0376218828199
-3.35356803866 -3.83027522936 -0.139201255191
-2.06645496493 -3.35356803866 -0.184501061958
-1.64759398951 -2.06645496493 -0.269247931912
-1.45519858411 -1.64759398951 -0.322290316312
-1.41729630208 -1.45519858411 -0.348129427421
-1.41425754719 -1.41729630208 -0.353162981611
-1.41421361026 -1.41425754719 -0.353547886593
-1.41421356237 -1.41421361026 -0.353553383485
-1.41421356237


Create a new paste based on this one


Comments: