Created
December 14, 2011 00:57
-
-
Save acbalingit/1474699 to your computer and use it in GitHub Desktop.
Set of root finders for AP155 - Functions and Roots Exercise
This file contains 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
#!/usr/bin/env python | |
import numpy as np | |
import matplotlib.pyplot as plt | |
from scipy.misc import * | |
import time | |
def func(x): | |
return x*x - 4*x*np.sin(x) +(2*np.sin(x))**2 | |
def deriv(x): | |
return 2**x - 4*np.sin(x) - 4*x*np.cos(x) + 2*(2*np.sin(x))*(2*np.cos(x)) | |
def bisection(f, a, c): | |
print "routine start"; old = 0 | |
while True: | |
b = (a + c)/2. | |
if f(a)*f(b) < 0: c = b | |
else: a = b | |
ans = f(b) | |
if old == ans: break | |
old = ans | |
return ans | |
def newton_raphson(func,start): | |
x = [-10, start] | |
while abs(x[1] - x[0]) > 1e-8: | |
x[0] = x[1] | |
x[1] = x[0] - func(x[0])/deriv(x[0]) | |
return x[1] | |
def secant(func,start): | |
x = [-10, start, -20] | |
while abs(x[2] - x[0]) > 1e-8: | |
x[2] = x[1] - func(x[1])*(x[1] - x[0])/(func(x[1]) - func(x[0])) | |
x[0], x[1] = x[1], x[2] | |
return x[1] | |
def hybrid(func, a, c): | |
x = [a, (a+c)/2., c] | |
while abs(func(x[1])) > 1e-8: | |
delta = func(x[1])/deriv(x[1]) | |
if (x[1] - delta) > x[0] and (x[1] - delta) < x[2]: | |
x[1] = x[1] - delta | |
else: | |
x[1] = (x[0] + x[2])/2. | |
if func(x[0])*func(x[1]) < 0: x[2] = x[1] | |
else: x[0] = x[1] | |
return x[1] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment