__file__ = "bisection.py" __description__ = "This is a function that calculates the roots of a polinomial function using the bisection numerical method" __version__ = "1.01" __usage__ = "bisection(rf,a,b,n,t)" __dependencies__ = "none" __python_version__ = "3.3.4" __author__ = "JJ.Cadavid - SFTC - EAFIT University" __date__ = "24/08/2014" #required modules %matplotlib inline import parser import matplotlib from sys import exit as error def bisection(rf,a,b,n,t): """Numerical method that finds roots of first grade polynomials""" f=parser.expr(rf).compile() #Parse string function into operable code by replacing x string with a number x=a; fa=eval(f); #f(a) interval eval x=b; fb=eval(f); #f(b) interval eval if ((fa*fb)>0): #Both images must cross the x-axis, a way to check is with sign sys.exit('[a,b] Interval does not cross the x-axis'); fp=10; i=0; while (abs(fp)>t): x=a+(b-a)/2; #Aproximation Calculation - changes every iteration fp=eval(f); print("f(p)={}".format(fp)); if(fa*fp)>0: a=x; else: b=x; if(i>n): print("p={}".format(x)); error('Tolerance not met by set iterations'); i=i+1 print("p={}".format(x)); return(x); function = "6.1*x + 23.64"; a = -5.0; b = 0.0; n = 10.0; t = 0.05; root = bisection(function, a, b, n, t); print(root); import matplotlib.pyplot as plt from numpy import linspace function=lambda x:6.1*x+23.64; # Function of obtained root x = linspace(a, b, 100); # x domain values defined by [a,b] interval y=function(x); font = {'family' : 'serif','color' : 'darkred', 'weight' : 'normal', 'size' : 16} # font used in axes legend plt.plot(x,y); plt.axis('auto') # according to list data, axes are adjust in the plot plt.title('First order polynomial root', fontdict=font); plt.text(-3, 12, r'$6.1x+23.64$', fontdict=font); plt.text(root, 0, r'$\circ$ Root', fontdict=font); plt.xlabel('x position [a.u]', fontdict=font); plt.ylabel('y position [a.u]', fontdict=font); plt.grid(); plt.show(); x = 0.64; # Asumiendo que la variable de la expresión es x. function_1 = ('1.2*x**3-0.6-x*2+0.85*x-78.9'); # Entrada de función polinómica tipo string function_1P = parser.expr(function_1).compile(); print("Parser evaluated -> {}".format(eval(function_1P))); function_2 = lambda x: 1.2*x**3-0.6-x*2+0.85*x-78.9; # Entrada de función polinómica como objeto matemático function_2P= function_2(x); print("Lambda evaluated -> {}".format(function_2P)); from numpy import arange AR=arange(0.0,11.0,1); print(AR); LN=linspace(0.0,10.0,11); print(LN); plt.plot(AR,LN,'ro') plt.show() # Cambiar el formato del documento from IPython.core.display import HTML def css_styling(): styles = open('../styles/custom_ketch.css', 'r').read() return HTML(styles) css_styling()