{"id":9960,"date":"2017-05-29T13:00:03","date_gmt":"2017-05-29T18:00:03","guid":{"rendered":"http:\/\/blog.espol.edu.ec\/analisisnumerico\/?p=9960"},"modified":"2026-03-09T19:48:08","modified_gmt":"2026-03-10T00:48:08","slug":"metodos-raices-graficos-animados","status":"publish","type":"post","link":"https:\/\/blog.espol.edu.ec\/algoritmos101\/mn-u02\/metodos-raices-graficos-animados\/","title":{"rendered":"2.7 M\u00e9todos de ra\u00edces y gr\u00e1ficos animados con Python"},"content":{"rendered":"\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<div class=\"wp-block-group has-medium-font-size is-layout-flex wp-block-group-is-layout-flex\">\n<p><a href=\"#biseccion\">Bisecci\u00f3n<\/a><\/p>\n\n\n\n<p><a href=\"#posicionfalsa\">Posici\u00f3n Falsa<\/a><\/p>\n\n\n\n<p><a href=\"#puntofijo\">Punto Fijo<\/a><\/p>\n\n\n\n<p><a href=\"#newtonraphson\">Newton-Raphson<\/a><\/p>\n\n\n\n<p><a href=\"#secante\">Secante<\/a><\/p>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<p>Solo para fines <strong>did\u00e1cticos<\/strong>, y como complemento para los <strong>ejercicios<\/strong> presentados en la unidad para ra\u00edces de ecuaciones, se presentan las instrucciones para las animaciones usadas en la presentaci\u00f3n de los conceptos y ejercicios.<strong> Los algoritmos para animaci\u00f3n NO son necesarios para realizar los ejercicios<\/strong>, que requieren una parte anal\u00edtica con al menos tres iteraciones en papel y l\u00e1piz. Se lo adjunta como una herramienta did\u00e1ctica de asistencia para las clases.<\/p>\n\n\n\n<p>La gr\u00e1fica (<code>graf_ani<\/code>) se crea en una ventana (<code>fig_ani<\/code>), inicializando con la linea a partir f(x) y configurando los par\u00e1metros base para el gr\u00e1fico.<\/p>\n\n\n\n<p>Se usan procedimientos para crear <code>unatrama()<\/code> para marca de iteraci\u00f3n y en cada cambio se limpia la trama manteniendo la base con <code>limpiatrama()<\/code>.<\/p>\n\n\n\n<p>En caso de requerir un archivo .gif animado se proporciona un nombre de archivo. Para crear el archivo se requiere de la librer\u00eda 'pillow',&nbsp;a ser instalado.<\/p>\n\n\n\n<p>otros ejemplos de animaci\u00f3n en el curso de Fundamentos de Programaci\u00f3n:<\/p>\n\n\n\n<p>Movimiento circular \u2013 Una part\u00edcula, animaci\u00f3n con matplotlib-Python<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<div class=\"wp-block-group has-medium-font-size is-layout-flex wp-block-group-is-layout-flex\">\n<p><a href=\"#biseccion\">Bisecci\u00f3n<\/a><\/p>\n\n\n\n<p><a href=\"#posicionfalsa\">Posici\u00f3n Falsa<\/a><\/p>\n\n\n\n<p><a href=\"#puntofijo\">Punto Fijo<\/a><\/p>\n\n\n\n<p><a href=\"#newtonraphson\">Newton-Raphson<\/a><\/p>\n\n\n\n<p><a href=\"#secante\">Secante<\/a><\/p>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"biseccion\">M\u00e9todo de la Bisecci\u00f3n y gr\u00e1fico animado con Python<\/h2>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"480\" src=\"http:\/\/blog.espol.edu.ec\/algoritmos101\/files\/2017\/05\/biseccion_animado.gif\" alt=\"m\u00e9todo de la bisecci\u00f3n gr\u00e1fica animada\" class=\"wp-image-13308\" \/><\/figure>\n\n\n\n<p>Instrucciones en Python<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code alignwide\"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Algoritmo de Bisecci\u00f3n, con tabla\n# Los valores de &#x5B;a,b] son aceptables\n# y seleccionados desde la gr\u00e1fica de la funci\u00f3n\n# error = tolera\nimport numpy as np\n \ndef biseccion(fx,a,b,tolera,iteramax = 50,\n                    vertabla=False, precision=6):\n    '''Algoritmo de Bisecci\u00f3n\n    Los valores de &#x5B;a,b] son seleccionados\n    desde la gr\u00e1fica de la funci\u00f3n\n    error = tolera\n    '''\n    fa = fx(a)\n    fb = fx(b)\n    tramo = np.abs(b-a)\n    itera = 0\n    cambia = np.sign(fa)*np.sign(fb)\n    tabla=&#x5B;]\n    if cambia&lt;0: # existe cambio de signo f(a) vs f(b)\n        if vertabla==True:\n            print('m\u00e9todo de Bisecci\u00f3n')\n            print('i', &#x5B;'a','c','b'],&#x5B; 'f(a)', 'f(c)','f(b)'])\n            print('  ','tramo')\n            np.set_printoptions(precision)\n             \n        while (tramo&gt;=tolera and itera&lt;=iteramax):\n            c = (a+b)\/2\n            fc = fx(c)\n            cambia = np.sign(fa)*np.sign(fc)\n            unafila = np.array(&#x5B;a,c,b,fa,fc,fb])\n            if (cambia&lt;0):\n                b = c\n                fb = fc\n            else:\n                a = c\n                fa = fc\n            tramo = np.abs(b-a)\n            unafila = np.concatenate(&#x5B;unafila,&#x5B;tramo]],axis=0)\n            tabla.append(unafila)\n            if vertabla==True:\n                print(itera,unafila&#x5B;0:3],unafila&#x5B;3:6])\n                print('  ',tramo)\n            itera = itera + 1\n        respuesta = c\n        # Valida respuesta\n        if (itera&gt;=iteramax):\n            respuesta = np.nan\n \n    else: \n        print(' No existe cambio de signo entre f(a) y f(b)')\n        print(' f(a) =',fa,',  f(b) =',fb) \n        respuesta=np.nan\n    tabla = np.array(tabla,dtype=float)\n    return(respuesta,tabla)\n \n# PROGRAMA ----------------------\n# INGRESO\nfx  = lambda x: x**3 + 4*x**2 - 10\na = 1\nb = 2\ntolera = 0.001\nitera = 0\nverdigitos = 4 # ver digitos en tabla\n \n# PROCEDIMIENTO\nc,tabla = biseccion(fx,a,b,tolera,\n                    vertabla=True,\n                    precision=verdigitos)\nn = len(tabla)\nerrado = tabla&#x5B;n-1,6]\n\n# SALIDA\nprint('M\u00e9todo de la Bisecci\u00f3n')\nprint('iteraciones:',n)\nprint('ra\u00edz en: ',c)\nprint('errado:',errado)\n\n# GRAFICA ---------------------\nimport matplotlib.pyplot as plt\n\nmuestras = 21 # en intervalo &#x5B;a,b]\nitera_graf = n-1 # iteraci\u00f3n en gr\u00e1fica\n\ntitulo = 'Bisecci\u00f3n'\nxk = np.linspace(a,b,muestras)\nfk = fx(xk)\n&#x5B;ai,ci,bi] = tabla&#x5B;itera_graf,0:3]\n&#x5B;fai,fci,fbi] = tabla&#x5B;itera_graf,3:6]\n\nplt.plot(xk,fk, label='f(x)')\n\nif itera_graf==(n-1): # iteraci\u00f3n final\n    plt.plot(c,0,'D',color='orange',label='c')\n\nif itera_graf&lt;(n-1): # una iteraci\u00f3n en gr\u00e1fica\n    titulo = titulo + ', itera='+str(itera_graf)\n    plt.plot(ai,fai,'o',color='red',label='a')\n    plt.plot(bi,fbi,'o',color='green',label='b')\n    plt.plot(ci,fci,'o',color='orange',label='c')\n\n    plt.plot(&#x5B;ai,ai],&#x5B;fai,0],'--',color='red')\n    plt.plot(&#x5B;bi,bi],&#x5B;fbi,0],'--',color='green')\n    plt.plot(&#x5B;ci,ci],&#x5B;fci,0],'--',color='orange')\n\nplt.axhline(0,color='gray')\nplt.xlabel('x')\nplt.ylabel('f(x)')\nplt.title(titulo)\nplt.grid()\nplt.legend()\n#plt.show()\n\n# GRAFICA CON ANIMACION ------------\nimport matplotlib.animation as animation\n \nxa = tabla&#x5B;:,0]\nya = tabla&#x5B;:,3]\nxb = tabla&#x5B;:,2]\nyb = tabla&#x5B;:,5]\nxc = tabla&#x5B;:,1]\nyc = tabla&#x5B;:,4]\n \n# Inicializa parametros de trama\/foto\nnarchivo = 'Bisecci\u00f3n' # nombre archivo\nretardo = 700 # milisegundos entre tramas\ntramas = len(xa)\n \n# GRAFICA animada en fig_ani\nfig_ani, graf_ani = plt.subplots()\nymax = np.max(fk)\nymin = np.min(fk)\ndeltax = np.abs(b-a)\ndeltay = np.abs(ymax-ymin)\ngraf_ani.set_xlim(&#x5B;a-0.05*deltax,b+0.05*deltax])\ngraf_ani.set_ylim(&#x5B;ymin-0.05*deltay,ymax+0.05*deltay])\nlinea0 = graf_ani.axhline(0, color='k')\n# Lineas y puntos base\nlineafx,= graf_ani.plot(xk,fk, label='f(x)')\n \npuntoa, = graf_ani.plot(xa&#x5B;0], ya&#x5B;0],'o',\n                        color='red', label='a')\npuntob, = graf_ani.plot(xb&#x5B;0], yb&#x5B;0],'o',\n                        color='green', label='b')\npuntoc, = graf_ani.plot(xc&#x5B;0], yc&#x5B;0],'o',\n                        color='orange', label='c')\nlineaa, = graf_ani.plot(&#x5B;xa&#x5B;0],xa&#x5B;0]],\n                        &#x5B;0,ya&#x5B;0]],color='red',\n                        linestyle='dashed')\nlineab, = graf_ani.plot(&#x5B;xb&#x5B;0],xb&#x5B;0]],\n                        &#x5B;0,yb&#x5B;0]],color='green',\n                        linestyle='dashed')\nlineac, = graf_ani.plot(&#x5B;xc&#x5B;0],xc&#x5B;0]],\n                        &#x5B;0,yc&#x5B;0]],\n                        color='orange',\n                        linestyle='dashed')\nlinea_ab, = graf_ani.plot(&#x5B;xa&#x5B;0],xb&#x5B;0]],\n                        &#x5B;0,0],\n                        color='yellow',\n                        linestyle='dotted')\n# Configura gr fica\ngraf_ani.set_title('Bisecci\u00f3n')\ngraf_ani.set_xlabel('x')\ngraf_ani.set_ylabel('f(x)')\ngraf_ani.legend()\ngraf_ani.grid()\n \n# Cada nueva trama\ndef unatrama(i,xa,ya,xb,yb,xc,yc):\n    # actualiza cada punto\n    puntoa.set_xdata(&#x5B;xa&#x5B;i]]) \n    puntoa.set_ydata(&#x5B;ya&#x5B;i]])\n    puntob.set_xdata(&#x5B;xb&#x5B;i]])\n    puntob.set_ydata(&#x5B;yb&#x5B;i]])\n    puntoc.set_xdata(&#x5B;xc&#x5B;i]])\n    puntoc.set_ydata(&#x5B;yc&#x5B;i]])\n    # actualiza cada linea\n    lineaa.set_ydata(&#x5B;ya&#x5B;i], 0])\n    lineaa.set_xdata(&#x5B;xa&#x5B;i], xa&#x5B;i]])\n    lineab.set_ydata(&#x5B;yb&#x5B;i], 0])\n    lineab.set_xdata(&#x5B;xb&#x5B;i], xb&#x5B;i]])\n    lineac.set_ydata(&#x5B;yc&#x5B;i], 0])\n    lineac.set_xdata(&#x5B;xc&#x5B;i], xc&#x5B;i]])\n    linea_ab.set_ydata(&#x5B;0, 0])\n    linea_ab.set_xdata(&#x5B;xa&#x5B;i], xb&#x5B;i]])\n    return (puntoa, puntob, puntoc, lineaa, lineab, lineac,linea_ab)\n \n# Limpia trama anterior\ndef limpiatrama():\n    puntoa.set_ydata(np.ma.array(xa, mask=True))\n    puntob.set_ydata(np.ma.array(xb, mask=True))\n    puntoc.set_ydata(np.ma.array(xc, mask=True))\n    lineaa.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    lineab.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    lineac.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    linea_ab.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    return (puntoa, puntob, puntoc, lineaa, lineab, lineac,linea_ab)\n \n# contador de tramas\ni = np.arange(0,tramas,1)\nani = animation.FuncAnimation(fig_ani,unatrama,\n                              i ,\n                              fargs=(xa, ya,\n                                     xb, yb,\n                                     xc, yc),\n                              init_func=limpiatrama,\n                              interval=retardo,\n                              blit=True)\n# Graba Archivo GIFAnimado y video\nani.save(narchivo+'_ani.gif', writer='pillow')\n#ani.save(narchivo+'_animado.mp4')\nplt.show()\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<div class=\"wp-block-group has-medium-font-size is-layout-flex wp-block-group-is-layout-flex\">\n<p><a href=\"#biseccion\">Bisecci\u00f3n<\/a><\/p>\n\n\n\n<p><a href=\"#posicionfalsa\">Posici\u00f3n Falsa<\/a><\/p>\n\n\n\n<p><a href=\"#puntofijo\">Punto Fijo<\/a><\/p>\n\n\n\n<p><a href=\"#newtonraphson\">Newton-Raphson<\/a><\/p>\n\n\n\n<p><a href=\"#secante\">Secante<\/a><\/p>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"posicionfalsa\">M\u00e9todo de la Posici\u00f3n Falsa y gr\u00e1fico animado con Python<\/h2>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"480\" src=\"http:\/\/blog.espol.edu.ec\/algoritmos101\/files\/2017\/05\/falsaposicion_animado.gif\" alt=\"m\u00e9todo de falsa posici\u00f3n gr\u00e1fico animado\" class=\"wp-image-13320\" \/><\/figure>\n\n\n\n<p>Instrucciones en Python<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code alignwide\"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# Algoritmo de falsa posicion para raices\n# &#x5B;a,b] se seleccionan de la gr\u00e1fica de f(x)\nimport numpy as np\n \ndef falsaposicion(fx,a,b,tolera,iteramax = 50,\n                  vertabla=False, precision=6):\n    '''fx en forma num\u00e9rica lambda\n    Los valores de &#x5B;a,b] son seleccionados\n    desde la gr\u00e1fica de la funci\u00f3n\n    error = tolera\n    '''\n    fa = fx(a)\n    fb = fx(b)\n    tramo = np.abs(b-a)\n    itera = 0\n    cambia = np.sign(fa)*np.sign(fb)\n    tabla=&#x5B;]\n \n    if cambia&lt;0: # existe cambio de signo f(a) vs f(b)\n        if vertabla==True:\n            print('m\u00e9todo de la Posici\u00f3n Falsa ')\n            print('i', &#x5B;'a','c','b'],&#x5B; 'f(a)', 'f(c)','f(b)'])\n            print('  ','tramo')\n            np.set_printoptions(precision)\n \n        while (tramo &gt;= tolera and itera&lt;=iteramax):\n            c = b - fb*(a-b)\/(fa-fb)\n            fc = fx(c)\n            cambia = np.sign(fa)*np.sign(fc)\n            unafila = np.array(&#x5B;a,c,b,fa,fc,fb])\n            if (cambia &gt; 0): # cambio de signo derecha\n                tramo = np.abs(c-a)\n                a = c\n                fa = fc\n            else: # cambio de signo izquierda\n                tramo = np.abs(b-c)\n                b = c\n                fb = fc\n\n            unafila = np.concatenate(&#x5B;unafila,&#x5B;tramo]],axis=0)\n            tabla.append(unafila)\n            if vertabla==True:\n                print(itera,unafila&#x5B;0:3],unafila&#x5B;3:6])\n                print('  ',tramo)\n            itera = itera + 1\n        respuesta = c\n        # Valida respuesta\n        if (itera&gt;=iteramax):\n            respuesta = np.nan\n    else: \n        print(' No existe cambio de signo entre f(a) y f(b)')\n        print(' f(a) =',fa,',  f(b) =',fb) \n        respuesta=np.nan\n    tabla = np.array(tabla,dtype=float)\n    return(respuesta,tabla)\n \n# PROGRAMA ----------------------\n# INGRESO\nfx  = lambda x: x**3 + 4*x**2 - 10\na = 1\nb = 2\ntolera = 0.0001\nverdigitos = 4 # ver digitos en tabla\n\n# PROCEDIMIENTO\nc,tabla = falsaposicion(fx,a,b,tolera,\n                        vertabla=True,\n                        precision=verdigitos)\nn = len(tabla)\nerrado = tabla&#x5B;n-1,6]\n\n# SALIDA\nprint('M\u00e9todo de la falsa posici\u00f3n')\nprint('iteraciones:',n)\nprint('ra\u00edz en: ',c)\nprint('errado:',errado)\n\n# GRAFICA ---------------------\nimport matplotlib.pyplot as plt\n \nmuestras = 21 # en intervalo &#x5B;a,b]\nitera_graf = n-1 # iteraci\u00f3n en gr\u00e1fica\n \ntitulo = 'Falsa Posici\u00f3n'\nxk = np.linspace(a,b,muestras)\nfk = fx(xk)\n&#x5B;ai,ci,bi] = tabla&#x5B;itera_graf,0:3]\n&#x5B;fai,fci,fbi] = tabla&#x5B;itera_graf,3:6]\n \nplt.plot(xk,fk, label='f(x)')\n \nif itera_graf==(n-1): # iteraci\u00f3n final\n    plt.plot(c,0,'D',color='orange',label='c')\n \nif itera_graf&lt;(n-1): # una iteraci\u00f3n en gr\u00e1fica\n    titulo = titulo + ', itera='+str(itera_graf)\n    plt.plot(ai,fai,'o',color='red',label='a')\n    plt.plot(bi,fbi,'o',color='green',label='b')\n    plt.plot(ci,fci,'o',color='orange',label='c')\n\n    plt.plot(&#x5B;ci,ci],&#x5B;fci,0],'--',color='orange')\n    plt.plot(&#x5B;ai,ai],&#x5B;fai,0],'--',color='red')\n    plt.plot(&#x5B;bi,bi],&#x5B;fbi,0],'--',color='green')\n    plt.plot(&#x5B;ai,bi],&#x5B;fai,fbi],color='orange')\n \nplt.axhline(0,color='gray')\nplt.xlabel('x')\nplt.ylabel('f(x)')\nplt.title(titulo)\nplt.grid()\nplt.legend()\nplt.tight_layout()\n# plt.show()\n\n# GRAFICA CON ANIMACION ------------\n#import matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n \nxa = tabla&#x5B;:,0]\nya = tabla&#x5B;:,3]\nxc = tabla&#x5B;:,1]\nyc = tabla&#x5B;:,4]\nxb = tabla&#x5B;:,2]\nyb = tabla&#x5B;:,5]\n \n# Inicializa parametros de trama\/foto\nnarchivo = 'PosicionFalsa' # nombre archivo\nretardo = 700 # milisegundos entre tramas\ntramas = len(xa)\n \n# GRAFICA animada en fig_ani\nfig_ani, graf_ani = plt.subplots()\ngraf_ani.set_xlim(&#x5B;a,b])\ngraf_ani.set_ylim(&#x5B;np.min(fk),np.max(fk)])\n# Lineas y puntos base\nlineafx, = graf_ani.plot(xk,fk,label ='f(x)')\n \npuntoa, = graf_ani.plot(xa&#x5B;0], ya&#x5B;0],'o',\n                        color='red', label='a')\npuntob, = graf_ani.plot(xb&#x5B;0], yb&#x5B;0],'o',\n                        color='green', label='b')\npuntoc, = graf_ani.plot(xc&#x5B;0], yc&#x5B;0],'o',\n                        color='orange', label='c')\n \nlineaab, = graf_ani.plot(&#x5B;xa&#x5B;0],xb&#x5B;0]],&#x5B;ya&#x5B;0],yb&#x5B;0]],\n                        color ='orange',\n                        label='y=mx+b')\nlineac0, = graf_ani.plot(&#x5B;xc&#x5B;0],xc&#x5B;0]],&#x5B;0,yc&#x5B;0]],\n                        color='magenta',\n                        linestyle='dashed')\n \n# Configura gr\u00e1fica\nlinea0 = graf_ani.axhline(0, color='k')\ngraf_ani.set_title('Posici\u00f3n Falsa')\ngraf_ani.set_xlabel('x')\ngraf_ani.set_ylabel('f(x)')\ngraf_ani.legend()\ngraf_ani.grid()\n \n# Cada nueva trama\ndef unatrama(i,xa,ya,xc,yc,xb,yb):\n    # actualiza cada punto, &#x5B;] porque es solo un valor\n    puntoa.set_xdata(&#x5B;xa&#x5B;i]])\n    puntoa.set_ydata(&#x5B;ya&#x5B;i]])\n    puntob.set_xdata(&#x5B;xb&#x5B;i]])\n    puntob.set_ydata(&#x5B;yb&#x5B;i]])\n    puntoc.set_xdata(&#x5B;xc&#x5B;i]])\n    puntoc.set_ydata(&#x5B;yc&#x5B;i]])\n    # actualiza cada linea\n    lineaab.set_ydata(&#x5B;ya&#x5B;i], yb&#x5B;i]])\n    lineaab.set_xdata(&#x5B;xa&#x5B;i], xb&#x5B;i]])\n    lineac0.set_ydata(&#x5B;0, yc&#x5B;i]])\n    lineac0.set_xdata(&#x5B;xc&#x5B;i], xc&#x5B;i]])  \n    return (puntoa, puntob, puntoc, lineaab,lineac0,)\n \n# Cada nueva trama\ndef limpiatrama():\n    puntoa.set_ydata(np.ma.array(xa, mask=True))\n    puntob.set_ydata(np.ma.array(xb, mask=True))\n    puntoc.set_ydata(np.ma.array(xc, mask=True))\n    lineaab.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    lineac0.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    return (puntoa, puntob, puntoc, lineaab,lineac0,)\n \n# contador de tramas\ni = np.arange(0, tramas,1)\nani = animation.FuncAnimation(fig_ani,unatrama,\n                              i ,\n                              fargs=(xa, ya,\n                                     xc, yc,\n                                     xb,yb),\n                              init_func=limpiatrama,\n                              interval=retardo,\n                              blit=True)\n# Graba Archivo GIFAnimado y video\nani.save(narchivo+'_ani.gif', writer='pillow')\n#ani.save(narchivo+'.mp4')\nplt.show()\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<div class=\"wp-block-group has-medium-font-size is-layout-flex wp-block-group-is-layout-flex\">\n<p><a href=\"#biseccion\">Bisecci\u00f3n<\/a><\/p>\n\n\n\n<p><a href=\"#posicionfalsa\">Posici\u00f3n Falsa<\/a><\/p>\n\n\n\n<p><a href=\"#puntofijo\">Punto Fijo<\/a><\/p>\n\n\n\n<p><a href=\"#newtonraphson\">Newton-Raphson<\/a><\/p>\n\n\n\n<p><a href=\"#secante\">Secante<\/a><\/p>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"puntofijo\">M\u00e9todo del Punto Fijo y gr\u00e1fico animado con Python<\/h2>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"480\" src=\"http:\/\/blog.espol.edu.ec\/algoritmos101\/files\/2017\/05\/puntofijo_converge_animado.gif\" alt=\"m\u00e9todo del punto fijo converge animado\" class=\"wp-image-13329\" \/><\/figure>\n\n\n\n<p>Instrucciones en Python<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code alignwide\"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# M\u00e9todo de Punto Fijo\n# El valor inicial de c se revisa con la gr\u00e1fica\nimport numpy as np\n \ndef puntofijo(gx,c,tolera,iteramax=50,vertabla=True, precision=6):\n    &quot;&quot;&quot;\n    g(x) se obtiene al despejar una x de f(x)\n    m\u00e1ximo de iteraciones predeterminado: iteramax\n    si no converge hasta iteramax iteraciones\n    la respuesta es NaN (Not a Number)\n    &quot;&quot;&quot;\n    itera = 0 # iteraci\u00f3n inicial\n    tramo = 2*tolera # al menos una iteracion\n\n    tabla=&#x5B;]\n    if vertabla==True:\n        print('M\u00e9todo del Punto Fijo')\n        print('i', &#x5B;'xi','gi','tramo'])\n        np.set_printoptions(precision)\n    \n    while (tramo&gt;=tolera and itera&lt;=iteramax):\n        gc = gx(c)\n        tramo = abs(gc-c)\n        \n        unafila = np.array(&#x5B;c,gc,tramo])\n        tabla.append(unafila)\n        if vertabla==True:\n            print(itera,unafila)\n        c = gc\n        itera = itera + 1\n    respuesta = c\n    # Valida respuesta\n    if itera&gt;=iteramax:\n        respuesta = np.nan\n        print('itera: ',itera,\n              'No converge,se alcanz\u00f3 el m\u00e1ximo de iteraciones')\n    tabla = np.array(tabla,dtype=float)\n    return(respuesta,tabla)\n\n# PROGRAMA ----------------------\n# INGRESO\nfx = lambda x: np.exp(-x) - x\ngx = lambda x: np.exp(-x)\n \nc = 0  # valor inicial\ntolera = 0.001\niteramax = 15\n \n# PROCEDIMIENTO\nc,tabla = puntofijo(gx,c,tolera,\n                    iteramax,vertabla=True)\nn = len(tabla)\nerrado = tabla&#x5B;n-1,2]\n\n# SALIDA\nprint('M\u00e9todo del Punto Fijo')\nprint('iteraciones:',n)\nprint('ra\u00edz en: ', c)\nprint('errado:',errado)\n\n# GRAFICA --------------------\nimport matplotlib.pyplot as plt\n \na = 0  # intervalo de gr\u00e1fica en &#x5B;a,b]\nb = 1\nmuestras = 21\nitera_graf = n-1 # iteraci\u00f3n en gr\u00e1fica\ntitulo = 'Punto Fijo'\n \n# calcula los puntos para fx y gx\nxk = np.linspace(a,b,muestras)\nfk = fx(xk)\ngk = gx(xk)\n\nplt.plot(xk,fk, label='f(x)',\n         linestyle='dashed')\nplt.plot(xk,gk, label='g(x)')\nplt.plot(xk,xk, label='y=x')\n\nif itera_graf==(n-1): # iteraci\u00f3n final\n    plt.plot(c,c,'D',color='orange',label='c')\n\n    plt.axvline(c, color='magenta',\n                linestyle='dotted')\nif itera_graf&lt;(n-1): # una iteraci\u00f3n en gr\u00e1fica\n    &#x5B;c,gc,tramo] = tabla&#x5B;itera_graf]\n    &#x5B;c1,gc1,tramo1] = tabla&#x5B;itera_graf+1]\n    titulo = titulo + ', itera='+str(itera_graf)\n    plt.plot(c,c,'o',color='red',label='c')\n    plt.plot(c,gc,'o',color='green',label='g(c)')\n    plt.plot(gc,gc,'o',color='orange',label='c&#x5B;i+1]')\n\n    dx = c1-c # largo de flecha\n    dy = gc-c\n    plt.arrow(c,c, 0,dy,\n              length_includes_head = True,\n              head_width = 0.05*abs(dy),\n              head_length = 0.1*abs(dy))\n    plt.arrow(c,gc,dx,0,\n              length_includes_head = True,\n              head_width = 0.05*abs(dx),\n              head_length = 0.1*abs(dx))\n    \nplt.axhline(0,color='gray')\nplt.xlabel('x')\nplt.ylabel('f(x)')\nplt.title(titulo)\nplt.grid()\nplt.legend()\nplt.tight_layout()\n#plt.show()\n \n# GRAFICA CON ANIMACION ------------\n#import matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n \nxc = tabla&#x5B;:,0]\nyc = tabla&#x5B;:,1]\n \n# Inicializa parametros de trama\/foto\nnarchivo = 'PuntoFijo' # nombre archivo\nretardo = 700 # milisegundos entre tramas\ntramas = len(xc)\n \n# GRAFICA animada en fig_ani\nfig_ani, graf_ani = plt.subplots()\ndx = np.abs(b-a)\ndy = np.abs(gx(b)-gx(a))\ngraf_ani.set_xlim(&#x5B;a-0.05*dx,b+0.05*dx])\ngraf_ani.set_ylim(&#x5B;np.min(fk)-0.05*dy,np.max(fk)+0.05*dy])\n \n# Lineas y puntos base\npuntoa,  = graf_ani.plot(xc&#x5B;0], yc&#x5B;0], 'ro')\npuntob,  = graf_ani.plot(xc&#x5B;0], xc&#x5B;0], 'go') # y=x\nlineafx, = graf_ani.plot(xk,fk, color='blue',\n                     linestyle='dashed', label='f(x)')\nlineagx, = graf_ani.plot(xk,gk, color='orange', label='g(x)')\nlineayx, = graf_ani.plot(xk,xk, color='green', label='y=x')\nlinearaiz = graf_ani.axvline(c, color='magenta',linestyle='dotted')\n \n# Configura gr\u00e1fica\nlinea0 = graf_ani.axhline(0, color='k')\ngraf_ani.set_title('Punto Fijo')\ngraf_ani.set_xlabel('x')\ngraf_ani.set_ylabel('f(x)')\ngraf_ani.legend()\ngraf_ani.grid()\n \n# Cada nueva trama\ndef unatrama(i,xc,yc):\n    # actualiza cada punto, &#x5B;] porque es solo un valor\n    puntoa.set_xdata(&#x5B;xc&#x5B;i]])\n    puntoa.set_ydata(&#x5B;yc&#x5B;i]])\n    puntob.set_xdata(&#x5B;xc&#x5B;i]]) # y=x\n    puntob.set_ydata(&#x5B;xc&#x5B;i]])\n     \n    # actualiza cada flecha\n    dx = xc&#x5B;i+1]-xc&#x5B;i]\n    dy = yc&#x5B;i]-xc&#x5B;i]\n    flecha01 = graf_ani.arrow(xc&#x5B;i],xc&#x5B;i], 0,dy,\n              length_includes_head = True,\n              head_width = 0.05*abs(dy),\n              head_length = 0.1*abs(dy))\n    flecha02 = graf_ani.arrow(xc&#x5B;i],yc&#x5B;i], dx,0,\n              length_includes_head = True,\n              head_width = 0.05*abs(dx),\n              head_length = 0.1*abs(dx))\n    return (puntoa, puntob, flecha01, flecha02)\n \n# Limpia trama anterior\ndef limpiatrama():\n    puntoa.set_ydata(np.ma.array(&#x5B;xc&#x5B;0]], mask=True))\n    puntob.set_ydata(np.ma.array(&#x5B;xc&#x5B;0]], mask=True))\n    return (puntoa, puntob)\n \n# contador de tramas\ni = np.arange(0, tramas-1,1)\nani = animation.FuncAnimation(fig_ani,unatrama,\n                              i ,\n                              fargs=(xc, yc),\n                              init_func=limpiatrama,\n                              interval=retardo,\n                              blit=True)\n# Graba Archivo GIFAnimado y video\nani.save(narchivo+'_ani.gif', writer='pillow')\n#ani.save(narchivo+'.mp4')\nplt.show()\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<div class=\"wp-block-group has-medium-font-size is-layout-flex wp-block-group-is-layout-flex\">\n<p><a href=\"#biseccion\">Bisecci\u00f3n<\/a><\/p>\n\n\n\n<p><a href=\"#posicionfalsa\">Posici\u00f3n Falsa<\/a><\/p>\n\n\n\n<p><a href=\"#puntofijo\">Punto Fijo<\/a><\/p>\n\n\n\n<p><a href=\"#newtonraphson\">Newton-Raphson<\/a><\/p>\n\n\n\n<p><a href=\"#secante\">Secante<\/a><\/p>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"newtonraphson\">M\u00e9todo de Newton-Raphson y gr\u00e1fico animado con Python<\/h2>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"480\" src=\"http:\/\/blog.espol.edu.ec\/algoritmos101\/files\/2017\/05\/newtonraphson_animado.gif\" alt=\"M\u00e9todo de Newton-Raphson gr\u00e1fico animado\" class=\"wp-image-13339\" \/><\/figure>\n\n\n<div class=\"wp-block-syntaxhighlighter-code alignwide\"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# M\u00e9todo de Newton-Raphson\n# Requiere fx y dfx\n# x0 es el valor inicial para la b\u00fasqueda de ra\u00edz\nimport numpy as np\n\ndef newton_raphson(fx,dfx,x0, tolera, iteramax=100,\n                   vertabla=False, precision=4):\n    '''fx y dfx en forma num\u00e9rica lambda\n    xi es el punto inicial de b\u00fasqueda\n    si no converge hasta iteramax iteraciones\n    la respuesta es NaN (Not a Number)\n    '''\n    itera=0\n    xi = x0\n    tramo = abs(2*tolera)\n    tabla=&#x5B;]\n    if vertabla==True:\n        print('M\u00e9todo de Newton-Raphson')\n        print('i', &#x5B;'xi','fi','dfi', 'xnuevo', 'tramo'])\n        np.set_printoptions(precision)\n    while (tramo&gt;=tolera):\n        fi = fx(xi)\n        dfi = dfx(xi)\n        xnuevo = xi - fi\/dfi\n        tramo = abs(xnuevo-xi)\n\n        unafila = np.array(&#x5B;xi,fi,dfi,xnuevo,tramo])\n        tabla.append(unafila)\n        if vertabla==True:\n            print(itera,np.array(&#x5B;xi,fi,dfi,xnuevo,tramo]))\n        xi = xnuevo\n        itera = itera + 1\n\n    if itera&gt;=iteramax:\n        xi = np.nan\n        print('itera: ',itera,\n              'No converge,se alcanz\u00f3 el m\u00e1ximo de iteraciones')\n    tabla = np.array(tabla,dtype=float)\n    return(xi,tabla)\n\n# PROGRAMA -------------------------\n# INGRESO\nfx  = lambda x: x**3 + 4*(x**2) - 10\ndfx = lambda x: 3*(x**2) + 8*x\n\nx0 = 2\ntolera = 0.001\niteramax = 15\nverdigitos = 4 # ver digitos en tabla\n\n# PROCEDIMIENTO\nxi,tabla = newton_raphson(fx,dfx,x0,tolera,iteramax,\n                          vertabla=True,\n                          precision=verdigitos)\nn = len(tabla)\nerrado = tabla&#x5B;n-1,4]\n\n# SALIDA\nprint('M\u00e9todo de Newton-Raphson')\nprint('itera  : ', n)\nprint('ra\u00edz en: ', xi)\nprint('errado : ', errado)\n\n# GRAFICA ---------------------\nimport matplotlib.pyplot as plt\n\na = 1\nb = 2\nmuestras = 21\nitera_graf = 2 #n-1 # iteraci\u00f3n en gr\u00e1fica\ntitulo = 'Newton-Raphson'\n\nxk = np.linspace(a,b,muestras)\nfk = fx(xk)\n\nxa = tabla&#x5B;:,0]\nya = tabla&#x5B;:,1]\nxb = tabla&#x5B;:,3]\ndfi = tabla&#x5B;:,2]\n# Aproximacion con tangente\nb0 = ya&#x5B;itera_graf] - dfi&#x5B;itera_graf]*xa&#x5B;itera_graf]\ntangentek = dfi&#x5B;itera_graf]*xk + b0\nci = -b0\/dfi&#x5B;itera_graf]\n\nplt.plot(xk,fk, label='f(x)')\nif itera_graf==(n-1): # iteraci\u00f3n final\n    plt.plot(xi,0, 'o')\nif itera_graf&lt;(n-1): # una iteraci\u00f3n en gr\u00e1fica\n    titulo = titulo+', itera='+str(itera_graf)\n    plt.ylim(&#x5B;np.min(fk),np.max(fk)])\n    plt.plot(&#x5B;xa&#x5B;itera_graf],xa&#x5B;itera_graf]],&#x5B;0,ya&#x5B;itera_graf]],'--',color='red')\n    plt.plot(xa&#x5B;itera_graf],ya&#x5B;itera_graf],'o',color='red',label='xi')\n    plt.plot(xk,tangentek,color='orange',label='tangente')\n    plt.plot(ci,0,'o',color='green',label='x&#x5B;i+1]')\n    \nplt.axhline(0)\nplt.xlabel('x')\nplt.ylabel('f(x)')\nplt.grid()\nplt.legend()\nplt.title(titulo)\nplt.tight_layout()\n#plt.show()\n\n# GRAFICA CON ANIMACION ------------\n#import matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n \nxa = tabla&#x5B;:,0]\nya = tabla&#x5B;:,1]\nxb = tabla&#x5B;:,3]\ndfi = tabla&#x5B;:,2]\n# Aproximacion con tangente\nb0 = ya&#x5B;0] - dfi&#x5B;0]*x0\ntangentei = dfi&#x5B;0]*xk + b0\nci = -b0\/dfi&#x5B;0]\n \n# Inicializa parametros de trama\/foto\nnarchivo = 'NewtonRaphson' # nombre archivo\nretardo = 700 # milisegundos entre tramas\ntramas = len(xa)\n \n# GRAFICA animada en fig_ani\nfig_ani, graf_ani = plt.subplots()\ngraf_ani.set_xlim(&#x5B;a,b])\ngraf_ani.set_ylim(&#x5B;np.min(fk),np.max(fk)])\n# Lineas y puntos base\nlineafx, = graf_ani.plot(xk,fk,label ='f(x)')\n \npuntoa, = graf_ani.plot(xa&#x5B;0], ya&#x5B;0],'o',\n                        color='red', label='x&#x5B;i]')\npuntob, = graf_ani.plot(xb&#x5B;0], 0,'o',\n                        color='green', label='x&#x5B;i+1]')\n \nlineatanx, = graf_ani.plot(xk,tangentei,\n                           color='orange',label='tangente')\nlineaa, = graf_ani.plot(&#x5B;xa&#x5B;0],xa&#x5B;0]],\n                        &#x5B;ya&#x5B;0],0], color='magenta',\n                        linestyle='dashed')\nlineab, = graf_ani.plot(&#x5B;xb&#x5B;0],xb&#x5B;0]],\n                         &#x5B;0,fx(xb&#x5B;0])], color='magenta',\n                         linestyle='dashed')\n# Configura gr\u00e1fica\nlinea0 = graf_ani.axhline(0, color='k')\ngraf_ani.set_title('Newton-Raphson')\ngraf_ani.set_xlabel('x')\ngraf_ani.set_ylabel('f(x)')\ngraf_ani.legend()\ngraf_ani.grid()\n \n# Cada nueva trama\ndef unatrama(i,xa,ya,xb,dfi):\n    # actualiza cada punto, &#x5B;] porque es solo un valor\n    puntoa.set_xdata(&#x5B;xa&#x5B;i]]) \n    puntoa.set_ydata(&#x5B;ya&#x5B;i]])\n    puntob.set_xdata(&#x5B;xb&#x5B;i]])\n    puntob.set_ydata(&#x5B;0])\n    # actualiza cada linea\n    lineaa.set_ydata(&#x5B;ya&#x5B;i], 0])\n    lineaa.set_xdata(&#x5B;xa&#x5B;i], xa&#x5B;i]])\n    lineab.set_ydata(&#x5B;0, fx(xb&#x5B;i])])\n    lineab.set_xdata(&#x5B;xb&#x5B;i], xb&#x5B;i]])\n    # Aproximacion con tangente\n    b0 = ya&#x5B;i] - dfi&#x5B;i]*xa&#x5B;i]\n    tangentei = dfi&#x5B;i]*xk+b0\n    lineatanx.set_ydata(tangentei)\n     \n    return (puntoa, puntob, lineaa, lineab,lineatanx,)\n \n# Limpia trama anterior\ndef limpiatrama():\n    puntoa.set_ydata(np.ma.array(xa, mask=True))\n    puntob.set_ydata(np.ma.array(xb, mask=True))\n    lineaa.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    lineab.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    lineatanx.set_ydata(np.ma.array(xk, mask=True))\n    return (puntoa, puntob, lineaa, lineab,lineatanx,)\n \n# contador de tramas\ni = np.arange(0,tramas,1)\nani = animation.FuncAnimation(fig_ani,unatrama,\n                              i ,\n                              fargs=(xa, ya,\n                                     xb, dfi),\n                              init_func=limpiatrama,\n                              interval=retardo,\n                              blit=True)\n# Graba Archivo GIFAnimado y video\nani.save(narchivo+'_ani.gif', writer='pillow')\n#ani.save(narchivo+'.mp4')\nplt.show()\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<div class=\"wp-block-group has-medium-font-size is-layout-flex wp-block-group-is-layout-flex\">\n<p><a href=\"#biseccion\">Bisecci\u00f3n<\/a><\/p>\n\n\n\n<p><a href=\"#posicionfalsa\">Posici\u00f3n Falsa<\/a><\/p>\n\n\n\n<p><a href=\"#puntofijo\">Punto Fijo<\/a><\/p>\n\n\n\n<p><a href=\"#newtonraphson\">Newton-Raphson<\/a><\/p>\n\n\n\n<p><a href=\"#secante\">Secante<\/a><\/p>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"secante\">M\u00e9todo de la Secante y gr\u00e1fico animado con Python<\/h2>\n\n\n\n<figure class=\"wp-block-image aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"640\" height=\"480\" src=\"http:\/\/blog.espol.edu.ec\/algoritmos101\/files\/2017\/05\/secantemetodo_ejercicio01_animado.gif\" alt=\"M\u00e9todo de la Secante gr\u00e1fico animado\" class=\"wp-image-13345\" \/><\/figure>\n\n\n\n<p>Instrucciones en Python<\/p>\n\n\n<div class=\"wp-block-syntaxhighlighter-code alignwide\"><pre class=\"brush: python; title: ; notranslate\" title=\"\">\n# M\u00e9todo de secante\n# Los valores de &#x5B;a,b] son revisados con la gr\u00e1fica\nimport numpy as np\n\ndef secante_raiz(fx,a,b,tolera, iteramax=50,\n                 vertabla=True, precision=6):\n    '''fx en forma num\u00e9rica lambda\n    Los valores de &#x5B;a,b] son seleccionados\n    desde la gr\u00e1fica de la funci\u00f3n\n    '''\n    xa = a\n    xb = b\n    itera = 0\n    tramo = np.abs(xb-xa)\n    tabla=&#x5B;]\n    if vertabla==True:\n        print('M\u00e9todo de la Secante')\n        print('i','&#x5B; x&#x5B;i-1], xi, x&#x5B;i+1], f&#x5B;i-1], fi , tramo]')\n        np.set_printoptions(precision)\n    \n    while not(tramo&lt;tolera or itera&gt;iteramax):\n        fa = fx(xa)\n        fb = fx(xb)\n        xc = xb - fb*(xa - xb)\/(fa - fb)\n        tramo = abs(xc - xb)\n\n        unafila = np.array(&#x5B;xa,xb,xc,fa,fb,tramo])\n        tabla.append(unafila)\n        if vertabla==True:\n            print(itera,unafila)\n        xa = xb\n        xb = xc\n        itera = itera + 1\n    \n    if itera&gt;=iteramax:\n        xc = np.nan\n        print('itera: ',itera,\n              'No converge,se alcanz\u00f3 el m\u00e1ximo de iteraciones')\n    respuesta = xc\n    tabla = np.array(tabla,dtype=float)\n    return(respuesta,tabla)\n\n# INGRESO\nfx = lambda x: x**3 + 4*x**2 - 10\na = 1\nb = 2\ntolera = 0.001\nverdigitos = 4 # ver digitos en tabla\niteramax = 50\n\n# PROCEDIMIENTO\nxc,tabla = secante_raiz(fx,a,b,tolera,iteramax,\n                        vertabla=True,\n                        precision=verdigitos)\nn = len(tabla)\nerrado = tabla&#x5B;n-1,5]\n# SALIDA\nprint('M\u00e9todo de la Secante')\nprint('iteraciones:',n)\nprint('ra\u00edz en: ',xc)\nprint('errado:',errado)\n\n# GRAFICA ---------------------\nimport matplotlib.pyplot as plt\n\na = 1\nb = 2\nmuestras = 21\nitera_graf = 0 #n-1 # iteraci\u00f3n en gr\u00e1fica\ntitulo = 'M\u00e9todo de la Secante'\ntramos = 100\n\n&#x5B;xa,xb,xc] = tabla&#x5B;itera_graf,0:3]\n&#x5B;fa,fb] = tabla&#x5B;itera_graf,3:5]\nxk = np.linspace(a,b,muestras)\nfk = fx(xk)\n\nplt.plot(xk,fk, label='f(x)')\n\nif itera_graf==(n-1): # iteraci\u00f3n final\n    plt.plot(xc,0,'D',color='orange',label='xc')\nif itera_graf&lt;(n-1): # una iteraci\u00f3n en gr\u00e1fica\n    titulo = titulo+', itera='+str(itera_graf)\n    plt.plot(xa, fa,'o',color='red', label='x&#x5B;i-1]')\n    plt.plot(xb, fb,'o',color='green', label='x&#x5B;i]')\n    plt.plot(xc, 0,'o',color='orange', label='x&#x5B;i+1]')\n\n    plt.plot(&#x5B;xa,xa],&#x5B;0,fa],'--',color='red')\n    plt.plot(&#x5B;xb,xb],&#x5B;0,fb],'--',color='green')\n\n    plt.plot(&#x5B;xa,xb],&#x5B;fa,fb],color='orange',label='secante ac')\n    plt.plot(&#x5B;xc,xb],&#x5B;0,fb],color='orange',label='secante cb')\n\nplt.axhline(0)\nplt.xlabel('x')\nplt.ylabel('f(x)')\nplt.grid()\nplt.legend()\nplt.title(titulo)\nplt.tight_layout()\n#plt.show()\n \n# GR\u00c1FICO CON ANIMACION ######\nimport matplotlib.animation as animation\n \nxa = tabla&#x5B;:,0]\nya = tabla&#x5B;:,3]\nxb = tabla&#x5B;:,1]\nyb = tabla&#x5B;:,4]\nxc = tabla&#x5B;:,2]\n \n# Inicializa parametros de trama\/foto\nnarchivo = 'SecanteMetodo' # nombre archivo\nretardo = 700 # milisegundos entre tramas\ntramas = len(xa)\n \n# GRAFICA animada en fig_ani\nfig_ani, graf_ani = plt.subplots()\ngraf_ani.set_xlim(&#x5B;a,b])\ngraf_ani.set_ylim(&#x5B;np.min(fk),np.max(fk)])\n \n# Lineas y puntos base\nlineafx, = graf_ani.plot(xk,fk,label ='f(x)')\n \npuntoa, = graf_ani.plot(xa&#x5B;0], ya&#x5B;0],'o',\n                        color='red', label='x&#x5B;i-1]')\npuntob, = graf_ani.plot(xb&#x5B;0], yb&#x5B;0],'o',\n                        color='green', label='x&#x5B;i]')\npuntoc, = graf_ani.plot(xc&#x5B;0], 0,'o',\n                        color='orange', label='x&#x5B;i+1]')\n \nlineatan1, = graf_ani.plot(&#x5B;xa&#x5B;0],xb&#x5B;0]],\n                           &#x5B;ya&#x5B;0],yb&#x5B;0]],\n                           color='orange',label='secante ac')\nlineatan2, = graf_ani.plot(&#x5B;xc&#x5B;0],xb&#x5B;0]],\n                           &#x5B;0,yb&#x5B;0]],\n                           color='orange',label='secante cb')\nlinea_a, = graf_ani.plot(&#x5B;xa&#x5B;0],xa&#x5B;0]],\n                         &#x5B;ya&#x5B;0],0], color='magenta',\n                         linestyle='dashed')\nlinea_b, = graf_ani.plot(&#x5B;xb&#x5B;0],xb&#x5B;0]],\n                         &#x5B;0,yb&#x5B;0]], color='magenta',\n                         linestyle='dashed')\n# Configura gr\u00e1fica\nlinea0 = graf_ani.axhline(0, color='k')\ngraf_ani.set_title('M\u00e9todo de la Secante')\ngraf_ani.set_xlabel('x')\ngraf_ani.set_ylabel('f(x)')\ngraf_ani.legend()\ngraf_ani.grid()\n \n# Cada nueva trama\ndef unatrama(i,xa,ya,xb,yb,xc):\n    # actualiza cada punto, &#x5B;] porque es solo un valor\n    puntoa.set_xdata(&#x5B;xa&#x5B;i]]) \n    puntoa.set_ydata(&#x5B;ya&#x5B;i]])\n    puntob.set_xdata(&#x5B;xb&#x5B;i]])\n    puntob.set_ydata(&#x5B;yb&#x5B;i]])\n    puntoc.set_xdata(&#x5B;xc&#x5B;i]])\n    puntoc.set_ydata(&#x5B;0])\n    # actualiza cada linea\n    linea_a.set_ydata(&#x5B;ya&#x5B;i], 0])\n    linea_a.set_xdata(&#x5B;xa&#x5B;i], xa&#x5B;i]])\n    linea_b.set_ydata(&#x5B;0, yb&#x5B;i]])\n    linea_b.set_xdata(&#x5B;xb&#x5B;i], xb&#x5B;i]])\n    lineatan1.set_ydata(&#x5B;ya&#x5B;i], 0])\n    lineatan1.set_xdata(&#x5B;xa&#x5B;i], xc&#x5B;i]])\n    lineatan2.set_ydata(&#x5B;0, yb&#x5B;i]])\n    lineatan2.set_xdata(&#x5B;xc&#x5B;i], xb&#x5B;i]])\n \n    return (puntoa, puntob, puntoc,\n            linea_a, linea_b,\n            lineatan1, lineatan2,)\n \n# Limpia trama anterior\ndef limpiatrama():\n    puntoa.set_ydata(np.ma.array(xa, mask=True))\n    puntob.set_ydata(np.ma.array(xb, mask=True))\n    puntoc.set_ydata(np.ma.array(xc, mask=True))\n    linea_a.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    linea_b.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    lineatan1.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    lineatan2.set_ydata(np.ma.array(&#x5B;0,0], mask=True))\n    return (puntoa, puntob, puntoc,\n            linea_a, linea_b,\n            lineatan1, lineatan2,)\n \n# contador de tramas\ni = np.arange(0,tramas,1)\nani = animation.FuncAnimation(fig_ani,unatrama,\n                              i ,\n                              fargs=(xa, ya,\n                                     xb, yb,\n                                     xc),\n                              init_func=limpiatrama,\n                              interval=retardo,\n                              blit=True)\n# Graba Archivo GIFAnimado y video\nani.save(narchivo+'_ani.gif', writer='pillow')\n#ani.save(narchivo+'.mp4')\nplt.show()\n\n<\/pre><\/div>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n\n\n\n<div class=\"wp-block-group has-medium-font-size is-layout-flex wp-block-group-is-layout-flex\">\n<p><a href=\"#biseccion\">Bisecci\u00f3n<\/a><\/p>\n\n\n\n<p><a href=\"#posicionfalsa\">Posici\u00f3n Falsa<\/a><\/p>\n\n\n\n<p><a href=\"#puntofijo\">Punto Fijo<\/a><\/p>\n\n\n\n<p><a href=\"#newtonraphson\">Newton-Raphson<\/a><\/p>\n\n\n\n<p><a href=\"#secante\">Secante<\/a><\/p>\n<\/div>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\" \/>\n","protected":false},"excerpt":{"rendered":"<p>Bisecci\u00f3n Posici\u00f3n Falsa Punto Fijo Newton-Raphson Secante Solo para fines did\u00e1cticos, y como complemento para los ejercicios presentados en la unidad para ra\u00edces de ecuaciones, se presentan las instrucciones para las animaciones usadas en la presentaci\u00f3n de los conceptos y ejercicios. Los algoritmos para animaci\u00f3n NO son necesarios para realizar los ejercicios, que requieren una [&hellip;]<\/p>\n","protected":false},"author":8043,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"wp-custom-template-entrada-mn-unidades","format":"standard","meta":{"footnotes":""},"categories":[36],"tags":[],"class_list":["post-9960","post","type-post","status-publish","format-standard","hentry","category-mn-u02"],"_links":{"self":[{"href":"https:\/\/blog.espol.edu.ec\/algoritmos101\/wp-json\/wp\/v2\/posts\/9960","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.espol.edu.ec\/algoritmos101\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.espol.edu.ec\/algoritmos101\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.espol.edu.ec\/algoritmos101\/wp-json\/wp\/v2\/users\/8043"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.espol.edu.ec\/algoritmos101\/wp-json\/wp\/v2\/comments?post=9960"}],"version-history":[{"count":11,"href":"https:\/\/blog.espol.edu.ec\/algoritmos101\/wp-json\/wp\/v2\/posts\/9960\/revisions"}],"predecessor-version":[{"id":22851,"href":"https:\/\/blog.espol.edu.ec\/algoritmos101\/wp-json\/wp\/v2\/posts\/9960\/revisions\/22851"}],"wp:attachment":[{"href":"https:\/\/blog.espol.edu.ec\/algoritmos101\/wp-json\/wp\/v2\/media?parent=9960"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.espol.edu.ec\/algoritmos101\/wp-json\/wp\/v2\/categories?post=9960"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.espol.edu.ec\/algoritmos101\/wp-json\/wp\/v2\/tags?post=9960"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}