Repaso de programación en Python

Funciones

def one():
    return "January"
def two():
    return "February"
def three():
    return "March"
def four():
    return "April"
def five():
    return "May"
def six():
    return "June"
def seven():
    return "July"
def eight():
    return "August"
def nine():
    return "September"
def ten():
    return "October"
def eleven():
    return "November"
def twelve():
    return "December"
def numbers_to_months(argument):
    switcher = {
        1: one,
        2: two,
        3: three,
        4: four,
        5: five,
        6: six,
        7: seven,
        8: eight,
        9: nine,
        10: ten,
        11: eleven,
        12: twelve
    }
    # Get the function from switcher dictionary
    func = switcher.get(argument, lambda: "Invalid month")
    # Execute the function
    return func()
numbers_to_months(13)
'Invalid month'
numbers_to_months(2)
'February'
def zero():
    return "zero"
def one():
    return "one"
def two():
    return "two"
switcher = {
        0: zero,
        1: one,
        2: two
    }
def numbers_to_strings(argument):
    # Get the function from switcher dictionary
    func = switcher.get(argument, lambda: "nothing")
    # Execute the function
    return func()
numbers_to_strings(4)
'nothing'

Números complejos

Z=complex(3)
Z
(3+0j)
Z.real, Z.imag, Z.conjugate()
(3.0, 0.0, (3-0j))

Función lambda

import scipy.integrate as scint
f=lambda t: t**2
scint.quad(f, 0, 1)
(0.33333333333333337, 3.700743415417189e-15)

Función filtro: aplica una función a los elementos de una lista y devuelve solamente los que devuelvan TRUE

l = [1, 2, 3]
filter(lambda t: t % 2.0 == 0, l)
<filter at 0x7fef28b81040>
l = [1,2,3,8,10,9]
list(filter(lambda t: t % 2.0 == 0, l))
[2, 8, 10]
creature_names = ['Sammy', 'Ashley', 'Jo', 'Olly', 'Jackie', 'Charlie']
print(list(filter(lambda x: x[0].lower() in 'aeiou', creature_names)))
['Ashley', 'Olly']

Función reduce: aplicar función a todos los elementos de una lista

l = [1,2,3]
from functools import reduce
reduce(lambda x, y: x+y, l)
6
l = [2,3,4]
reduce(lambda x, y: x*y, l)
24
print("The maximum element of the list is : ", end="")
print(reduce(lambda a, b: a if a > b else b, l))
The maximum element of the list is : 4

Listas

[n for n in l if n % 2.0 == 0]
[2, 4]
l = [0, 1, 2, 3]
m = ["a", "b"]
n = [s * v for s in m for v in l if v > 0]
n
['a', 'aa', 'aaa', 'b', 'bb', 'bbb']
A = [0, 1, 2, 3]
B = [5, 6, 7]
[s * v for s in A for v in B if s > 0]
[5, 6, 7, 10, 12, 14, 15, 18, 21]
A = [0, 1, 2, 3]
B = [5, 6, 7]
[s * v for s in A for v in B if s > -1]
[0, 0, 0, 5, 6, 7, 10, 12, 14, 15, 18, 21]

Tuplas

l2 = (n ** 2 for n in l)
for ele in l2:
    print (ele)
0
1
4
9

Ficheros I/O

fich = open("./files/Prueba.txt", "r") 
for linea in fich:
    print(linea, end="")
¡Ay mísero de mí, y ay, infelice!

Apurar, cielos, pretendo,
ya que me tratáis así
qué delito cometí
contra vosotros naciendo;
aunque si nací, ya entiendo
qué delito he cometido.
Bastante causa ha tenido
vuestra justicia y rigor;
pues el delito mayor
del hombre es haber nacido.
fich = open("./files/Prueba.txt", "r") 
print(fich.readlines())
['¡Ay mísero de mí, y ay, infelice!\n', '\n', 'Apurar, cielos, pretendo,\n', 'ya que me tratáis así\n', 'qué delito cometí\n', 'contra vosotros naciendo;\n', 'aunque si nací, ya entiendo\n', 'qué delito he cometido.\n', 'Bastante causa ha tenido\n', 'vuestra justicia y rigor;\n', 'pues el delito mayor\n', 'del hombre es haber nacido.\n']
fich = open("./files/Prueba2.txt", "w")
fich.writelines(["Prueba de escritura 1\n", "Prueba de escritura 2\n"])
fich.close()

Pandas

import pandas as pd
df = pd.read_csv('./files/Prueba.csv')
df.values
array([[ 1, 11, 41],
       [ 2, 12, 42],
       [ 3, 13, 43],
       [ 4, 14, 44],
       [ 5, 15, 45]])
df.head()
Columna1 Columna2 Columna3
0 1 11 41
1 2 12 42
2 3 13 43
3 4 14 44
4 5 15 45

Funciones

import math as mt
def elevado(a, k):
    productorio = 1.0
    for i in range(k):
        productorio *= a
    return productorio

def factorial(k):
    productorio = 1.0
    for i in range(2, k+1):
        productorio *= i
    return productorio

def exponencial(a, n):
    sumatorio = 0.0
    for k in range(n):
        sumatorio += elevado(a, k) / factorial(k)
        ##print(sumatorio, k, elevado(a, k), factorial(k))
    return sumatorio

exponencial(2,17), mt.exp(2)
(7.389056098516415, 7.38905609893065)
import math as mt
def biseccion(f, a, b, epsilon):
    if f(a)*f(b) > 0:
        return False, x1
    c = (a + b) / 2.0
    iter_t=0
    while mt.fabs(f(c))> epsilon:
        #print(a, b, c, f(a), f(b), f(c))
        iter_t+=1
        if f(a)*f(c) < 0:
            b = c
        elif f(c)*f(b) < 0:
            a = c
        c = (a + b) / 2.0
    print(iter_t)
    return True, c

biseccion(lambda x: x**10 - 1, 0, 1.3, 10**(-9))
31
(True, 1.0000000000232832)
import math as mt
def biseccion(f, a, b, epsilon):
    if f(a)*f(b) > 0:
        return False, x1
    c = (a + b) / 2.0
    iter_t=0
    while mt.fabs(f(c))> epsilon:
        #print(a, b, c, f(a), f(b), f(c))
        iter_t+=1
        if f(a)*f(c) < 0:
            b = c
        elif f(c)*f(b) < 0:
            a = c
        c = (a + b) / 2.0
    print(iter_t)
    return True, c

def fun(x):
    return x**10-1

biseccion(fun, 0, 1.3, 10**(-9))
31
(True, 1.0000000000232832)
import math as mt
def regulafalsa(f, a, b, epsilon):
    if f(a)*f(b) > 0:
        return False, a
    c_ant=a
    c = b - f(b)*(a-b)/(f(a)-f(b))
    iter_t=0
    while mt.fabs((c-c_ant)/c) > epsilon:
        iter_t+=1
        #print(a, b, c, f(a), f(b), f(c))
        if f(a)*f(c) < 0:
            b = c
        elif f(c)*f(b) < 0:
            a = c
        c_ant=c
        c = b - f(b)*(a-b)/(f(a)-f(b))
    print(iter_t)
    return True, c
def regulafalsaMod(f, a, b, epsilon):
    if f(a)*f(b) > 0:
        return False, a
    c_ant=a
    c = b - f(b)*(a-b)/(f(a)-f(b))
    iter_a=0
    iter_b=0
    iter_t=0
    while mt.fabs(c-c_ant) > epsilon:
        iter_t+=1
        #print(a, b, c, f(a), f(b), f(c))
        if f(a)*f(c) < 0:
            b = c
            iter_b=0
            iter_a+=1
            if (iter_a>=2): a=a/2
        elif f(c)*f(b) < 0:
            a = c
            iter_a=0
            iter_b+=1
            if (iter_b>=2): b=b/2
        c_ant=c
        c = b - f(b)*(a-b)/(f(a)-f(b))
    print(iter_t)
    return True, c

regulafalsaMod(lambda x: x**10 - 1, 0, 1.3, 10**(-9))
4
(True, 0.1817588725191044)

Recursión

import math as mt
def regulafalsa(f, a, b, epsilon):
    if f(a)*f(b) > 0:
        return False, x1
    c_ant = a
    c = b - f(b)*(a-b)/(f(a)-f(b))
    ##print(a, b, c, f(a), f(b), f(c))
    if mt.fabs((c-c_ant)/c) < epsilon:
        return True, c
    elif f(a)*f(c) < 0:
        return regulafalsa(f, a, c, epsilon)
    else:
        return regulafalsa(f, c, b, epsilon)

regulafalsa(lambda x: x**10 - 1, 0, 1.3, 10**(-9))
(True, 0.9999999968380443)
import math as mt
def biseccion(f, a, b, epsilon):
    if f(a)*f(b) > 0:
        return False, x1
    c = (a + b) / 2.0
    # criterio de parada, para evitar entrar en buble infinito
    if mt.fabs(f(c))< epsilon:
        return True, c
    print(a, b, c, f(a), f(b), f(c))
    # si no paramos, nueva llamada
    if f(a)*f(c) < 0:
        b = c
    elif f(c)*f(b) < 0:
        a = c
    return biseccion(f,a,b,epsilon)

def fun(x):
    return x**10-1

biseccion(fun, 0, 1.3, 10**(-9))
0 1.3 0.65 -1 12.785849184900005 -0.9865372566553711
0.65 1.3 0.9750000000000001 -0.9865372566553711 12.785849184900005 -0.22367037914356147
0.9750000000000001 1.3 1.1375000000000002 -0.22367037914356147 12.785849184900005 2.626720217225217
0.9750000000000001 1.1375000000000002 1.0562500000000001 -0.22367037914356147 2.626720217225217 0.7284913860640538
0.9750000000000001 1.0562500000000001 1.015625 -0.22367037914356147 0.7284913860640538 0.1677068465489142
0.9750000000000001 1.015625 0.9953125 -0.22367037914356147 0.1677068465489142 -0.04589848926847229
0.9953125 1.015625 1.00546875 -0.04589848926847229 0.1677068465489142 0.05605314088389357
0.9953125 1.00546875 1.000390625 -0.04589848926847229 0.05605314088389357 0.003913123612528047
0.9953125 1.000390625 0.9978515625000001 -0.04589848926847229 0.003913123612528047 -0.0212778502779869
0.9978515625000001 1.000390625 0.9991210937500001 -0.0212778502779869 0.003913123612528047 -0.00875438241808546
0.9991210937500001 1.000390625 0.9997558593750001 -0.00875438241808546 0.003913123612528047 -0.0024387257864679768
0.9997558593750001 1.000390625 1.0000732421875 -0.0024387257864679768 0.003913123612528047 0.0007326633209661093
0.9997558593750001 1.0000732421875 0.9999145507812501 -0.0024387257864679768 0.0007326633209661093 -0.0008541636917527295
0.9999145507812501 1.0000732421875 0.9999938964843751 -0.0008541636917527295 0.0007326633209661093 -6.103347989572239e-05
0.9999938964843751 1.0000732421875 1.0000335693359377 -6.103347989572239e-05 0.0007326633209661093 0.0003357440744307105
0.9999938964843751 1.0000335693359377 1.0000137329101564 -6.103347989572239e-05 0.0003357440744307105 0.0001373375885516115
0.9999938964843751 1.0000137329101564 1.0000038146972656 -6.103347989572239e-05 0.0001373375885516115 3.8147627499096615e-05
0.9999938964843751 1.0000038146972656 0.9999988555908204 -6.103347989572239e-05 3.8147627499096615e-05 -1.1444032861351872e-05
0.9999988555908204 1.0000038146972656 1.0000013351440429 -1.1444032861351872e-05 3.8147627499096615e-05 1.3351520646409654e-05
0.9999988555908204 1.0000013351440429 1.0000000953674317 -1.1444032861351872e-05 1.3351520646409654e-05 9.536747265226353e-07
0.9999988555908204 1.0000000953674317 0.999999475479126 -1.1444032861351872e-05 9.536747265226353e-07 -5.245196359138227e-06
0.999999475479126 1.0000000953674317 0.9999997854232789 -5.245196359138227e-06 9.536747265226353e-07 -2.1457651386835863e-06
0.9999997854232789 1.0000000953674317 0.9999999403953553 -2.1457651386835863e-06 9.536747265226353e-07 -5.960462867715677e-07
0.9999999403953553 1.0000000953674317 1.0000000178813935 -5.960462867715677e-07 9.536747265226353e-07 1.788139492031604e-07
0.9999999403953553 1.0000000178813935 0.9999999791383745 -5.960462867715677e-07 1.788139492031604e-07 -2.0861623584167432e-07
0.9999999791383745 1.0000000178813935 0.999999998509884 -2.0861623584167432e-07 1.788139492031604e-07 -1.4901160194646934e-08
0.999999998509884 1.0000000178813935 1.0000000081956388 -1.4901160194646934e-08 1.788139492031604e-07 8.195639145114342e-08
0.999999998509884 1.0000000081956388 1.0000000033527614 -1.4901160194646934e-08 8.195639145114342e-08 3.3527614462514066e-08
0.999999998509884 1.0000000033527614 1.0000000009313226 -1.4901160194646934e-08 3.3527614462514066e-08 9.313225746154785e-09
0.999999998509884 1.0000000009313226 0.9999999997206033 -1.4901160194646934e-08 9.313225746154785e-09 -2.7939672797572257e-09
0.9999999997206033 1.0000000009313226 1.0000000003259628 -2.7939672797572257e-09 9.313225746154785e-09 3.259628122975755e-09
(True, 1.0000000000232832)

Cálculo numérico

  • raíces de ecuaciones

  • derivación numérica

  • integración numérica

  • métodos numéricos para EDOs

import math as mt
def iteraPuntoFijo(g, x, epsilon, max_iter):
    iter_t=0
    while mt.fabs((g(x)-x)/g(x))> epsilon and iter_t<max_iter:
        iter_t+=1
        x=g(x)
    print(iter_t)
    return x

iteraPuntoFijo(lambda x: mt.exp(-x), 0, 10**(-9), 200)
38
0.5671432901223239
import math as mt
def newtonRaphson(f, fd, x, epsilon):
    iter_t=0
    x_ant = x + 2*epsilon
    while mt.fabs(x_ant-x)> epsilon:
        iter_t+=1
        x_ant = x
        if fd(x)==0: return False, x
        x=x-f(x)/fd(x)
    print(iter_t)
    return True, x

newtonRaphson(lambda x: mt.exp(-x)-x, lambda x: -mt.exp(-x)-1,0, 10**(-9))
5
(True, 0.567143290409784)
import math as mt
def secante(f, x_ant, x, epsilon):
    iter_t=0
    while mt.fabs(x_ant-x)> epsilon:
        print(x)
        iter_t+=1
        if (f(x_ant)==f(x)): return False, x
        x_new=x-f(x)*(x_ant-x)/(f(x_ant)-f(x))
        x_ant=x
        x=x_new
    print(iter_t)
    return True, x

secante(lambda x: mt.exp(-x)-x, 0, 1, 10**(-12))
1
0.6126998367802821
0.5638383891610742
0.5671703584197446
0.5671433066049633
0.5671432904097046
6
(True, 0.5671432904097838)
import math as mt
def secanteMod(f, x, epsilon):
    iter_t=0
    x_ant = x + 2*epsilon
    while mt.fabs(x_ant-x)> epsilon:
        iter_t+=1
        x_ant = x
        if f(x+epsilon)==f(x): return False, x
        x=x-f(x)*epsilon/(f(x+epsilon)-f(x))
    print(iter_t)
    return True, x

secanteMod(lambda x: mt.exp(-x)-x, 0, 10**(-9))
5
(True, 0.5671432904097838)
import math as mt
def newtonRaphsonMod(f, x, eps, iter_max):
    iter_t=0
    x_ant = x + 2*eps
    diferen = lambda f, x, eps: (f(x+eps)-f(x))/eps
    difSegunda = lambda f, x, eps: (f(x+eps)-2*f(x)+f(x-eps))/(eps*eps)
    while mt.fabs(x_ant-x)> eps and iter_t<iter_max:
        #print(iter_t, x)
        iter_t+=1
        x_ant = x
        print("i", iter_t, "x", x, "dif2", difSegunda(f,x,eps), "dif", diferen(f,x,eps), "f", f(x))
        if diferen(f,x,eps)**2==f(x)*difSegunda(f,x,eps): return False, x
        x=x-f(x)*diferen(f,x,eps)/(diferen(f,x,eps)**2-f(x)*difSegunda(f,x,eps))
    print(iter_t)
    return True, x

newtonRaphsonMod(lambda x: (x-3)*(x-1)*(x-1),0, 10**(-6), 100)
i 1 x 0 dif2 -9.99955673819386 dif 6.999995000089854 f -3
i 2 x 1.105189089355384 dif2 -3.368867684816479 dif -0.3875638082649624 f -0.020965598638882667
i 3 x 1.0030782671025074 dif2 -3.9815303933324593 dif -0.012286631988153052 f -1.8922287885892526e-05
i 4 x 1.0000038677348835 dif2 -3.999976792932577 dif -1.7470882050986708e-05 f -2.9918688398857965e-11
i 5 x 1.0000010507890613 dif2 -3.9999936946075003 dif -6.203148779759915e-06 f -2.2083141425373897e-12
5
(True, 1.0000005887170116)

Integración numérica

def trapecio(f, a, b, n):
    eps = 10**(-6)
    difSegunda = lambda f, x, eps: (f(x+eps)-2*f(x)+f(x-eps))/(eps*eps)
    h=(b-a)/n
    integral = (b-a)*(f(a)+ f(b) + 2*sum([f(a+(i+1)*h) for i in range(n)]))/(2*n)
    error = - sum([difSegunda(f, a+(i+1)*h, eps) for i in range(n)])*(b-a)**3/(12*n**3)
    return error, integral
trapecio(lambda x: x**2, 1, 2, 1000)
(-1.6666669896044559e-07, 2.337333499999998)
import scipy.integrate as scint
scint.quad(lambda x: x**2,1,2)
(2.3333333333333335, 2.590520390792032e-14)
def simpson(f, a, b, n):
    eps = 10**(-10)
    dif_4 = lambda f, x, eps: (f(x+4*eps)-4*f(x+3*eps)+6*f(x+2*eps)-4*f(x+eps)+f(x))/(eps**4)
    h=(b-a)/n
    integral = (b-a)*sum([f(a+2*(i-1)*h) + 4*f(a+(2*i-1)*h) + f(a+2*i*h) for i in range(1, int(n/2)+1)])/(3*n)
    print([dif_4(f, a+(2*i-1)*h, eps) for i in range(int(n/2)+1)])
    error = - sum([dif_4(f, a+(2*i-1)*h, eps) for i in range(int(n/2)+1)])*(b-a)**5/(90*n**5)
    return error, integral
simpson(lambda x: x**2, 1, 2, 10)
[0.0, 2.220446049250313e+24, -2.220446049250313e+24, 0.0, 0.0, 4.440892098500626e+24]
(-4.934324553889584e+17, 2.3333333333333335)
def riemann(f, a, b, N):  
    suma = 0
    h = (b-a)/N
    for i in range(N):
        izq = a + i*h 
        der = izq + h
        medio = (izq + der)/2
        suma += f(medio)*h
    return suma 
def f(t):
    return t**2

riemann(f, 0, 1, 25)
0.3332
def riemann2(f, a, b, N):  
    suma = 0
    h = (b-a)/N
    print (  sum([f(a+i*h)*h for i in range(N)]))
    for i in range(N):
        izq = a + i*h 
        der = izq + h
        medio = (izq + der)/2
        suma += f(medio)*h
    return suma 
riemann2(f, 0, 1, 25)
0.31360000000000005
0.3332
def euler(f,x0,y0,xn,h):
    n=int((xn-x0)/h)
    x=[x0];y=[y0]
    for i in range(n):
        y.append(y[i]+f(x[i],y[i])*h)
        x.append(x[i]+h)
    return x, y
x, y_eul = euler(lambda x, y: -2*x**3+12*x**2-20*x+8.5, 0, 1, 4, 0.5)
import math as mt
def heun(f,x0,y0,xn,h):
    n=int((xn-x0)/h)
    x=[x0];y=[y0]
    for i in range(n):
        wy=y[i]+f(x[i],y[i])*h
        m = (f(x[i],y[i])+f(x[i]+h,wy))/2
        y.append(y[i]+m*h)
        x.append(x[i]+h)
    return x, y
x, y_heu = heun(lambda x, y: 4*mt.exp(0.8*x)-0.5*y, 0, 2, 4, 1)
def runge2(f,x0,y0,xn,h):
    n=int((xn-x0)/h)
    x=[x0];y=[y0]
    for i in range(n):
        k1=f(x[i],y[i])
        k2=f(x[i]+(3/4)*h,y[i]+(3/4)*k1*h)
        y.append(y[i]+(k1/3+2*k2/3)*h)
        x.append(x[i]+h)
    return x, y
runge2(lambda x, y: -2*x**3+12*x**2-20*x+8.5, 0, 1, 4, 0.5)
([0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],
 [1,
  3.27734375,
  3.1015625,
  2.34765625,
  2.140625,
  2.85546875,
  4.1171875,
  4.80078125,
  3.03125])
def runge2(f,x0,y0,xn,h):
    n=int((xn-x0)/h)
    x=[x0 + i*h for i in range(n+1)]
    y=[x[ix-1]+(f(x[ix-1],x[ix-1])/3+2*x0/3)*h if ix>0 else y0 for ix, num in enumerate(x)]
    return x, y
runge2(lambda x, y: -2*x**3+12*x**2-20*x+8.5, 0, 1, 4, 0.5)
([0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0],
 [1,
  1.4166666666666667,
  0.7083333333333334,
  0.75,
  1.2916666666666667,
  2.0833333333333335,
  2.875,
  3.4166666666666665,
  3.4583333333333335])
#A = ['A','B','C','D','E','F','G','H','I','J']
# [(x, A[i+1] if (i+1) < len(A) else None) for i,x in enumerate(A)]
# return sum([x if x!=13 and nums[idx-1 if idx >0 else 0] !=13 else 0 for idx,x in enumerate(nums)])
import math as mt
def maxSeccionAurea(f,a,b, eps, maxIter):
    i=0
    R=(mt.sqrt(5)-1)/2
    err=2*eps
    opti=a
    while i<maxIter and err>eps:
        d=R*(b-a)
        x1=a+d
        x2=b-d
        i+=1
        print(i, round(a,4), round(f(a),4), round(x2,4), round(f(x2),4), round(x1,4), round(f(x1),4), round(b,4), round(f(b),4), round(d,4), err)
        if f(x1)>f(x2):
            a=x2
            opti=x1
        elif f(x2)>f(x1):
            b=x1
            opti=x2
        err = (1-R)*mt.fabs((b-a)/opti)
    return opti
maxSeccionAurea(lambda x: 2*mt.sin(x)-x**2/10, 0, 4, 10**(-6), 2000)
1 0 0.0 1.5279 1.7647 2.4721 0.63 4 -3.1136 2.4721 2e-06
2 0 0.0 0.9443 1.531 1.5279 1.7647 2.4721 0.63 1.5279 0.6180339887498949
3 0.9443 1.531 1.5279 1.7647 1.8885 1.5432 2.4721 0.63 0.9443 0.3819660112501051
4 0.9443 1.531 1.305 1.7595 1.5279 1.7647 1.8885 1.5432 0.5836 0.23606797749978972
5 1.305 1.7595 1.5279 1.7647 1.6656 1.7136 1.8885 1.5432 0.3607 0.1458980337503155
6 1.305 1.7595 1.4427 1.7755 1.5279 1.7647 1.6656 1.7136 0.2229 0.09016994374947428
7 1.305 1.7595 1.3901 1.7742 1.4427 1.7755 1.5279 1.7647 0.1378 0.059016994374947486
8 1.3901 1.7742 1.4427 1.7755 1.4752 1.7732 1.5279 1.7647 0.0851 0.03647450843757889
9 1.3901 1.7742 1.4226 1.7757 1.4427 1.7755 1.4752 1.7732 0.0526 0.02254248593736858
10 1.3901 1.7742 1.4102 1.7754 1.4226 1.7757 1.4427 1.7755 0.0325 0.014128866181757014
11 1.4102 1.7754 1.4226 1.7757 1.4303 1.7757 1.4427 1.7755 0.0201 0.008732119522824787
12 1.4226 1.7757 1.4303 1.7757 1.435 1.7757 1.4427 1.7755 0.0124 0.005367778120295635
13 1.4226 1.7757 1.4274 1.7757 1.4303 1.7757 1.435 1.7757 0.0077 0.0033174693224107257
14 1.4226 1.7757 1.4256 1.7757 1.4274 1.7757 1.4303 1.7757 0.0047 0.0020545212007783056
15 1.4256 1.7757 1.4274 1.7757 1.4285 1.7757 1.4303 1.7757 0.0029 0.0012697639326882445
16 1.4256 1.7757 1.4267 1.7757 1.4274 1.7757 1.4285 1.7757 0.0018 0.0007847572680900612
17 1.4267 1.7757 1.4274 1.7757 1.4278 1.7757 1.4285 1.7757 0.0011 0.0004850066645981833
18 1.4267 1.7757 1.4271 1.7757 1.4274 1.7757 1.4278 1.7757 0.0007 0.0002997506034918779
19 1.4271 1.7757 1.4274 1.7757 1.4275 1.7757 1.4278 1.7757 0.0004 0.00018525606110624606
20 1.4274 1.7757 1.4275 1.7757 1.4276 1.7757 1.4278 1.7757 0.0003 0.0001144814348860735
21 1.4274 1.7757 1.4275 1.7757 1.4275 1.7757 1.4276 1.7757 0.0002 7.075341784047577e-05
22 1.4275 1.7757 1.4275 1.7757 1.4276 1.7757 1.4276 1.7757 0.0001 4.372801704565714e-05
23 1.4275 1.7757 1.4276 1.7757 1.4276 1.7757 1.4276 1.7757 0.0001 2.702467044232797e-05
24 1.4275 1.7757 1.4276 1.7757 1.4276 1.7757 1.4276 1.7757 0.0 1.670216486813883e-05
25 1.4275 1.7757 1.4275 1.7757 1.4276 1.7757 1.4276 1.7757 0.0 1.0322612129410393e-05
26 1.4275 1.7757 1.4276 1.7757 1.4276 1.7757 1.4276 1.7757 0.0 6.379725148638679e-06
27 1.4275 1.7757 1.4275 1.7757 1.4276 1.7757 1.4276 1.7757 0.0 3.942886980712303e-06
28 1.4275 1.7757 1.4276 1.7757 1.4276 1.7757 1.4276 1.7757 0.0 2.4368381678669634e-06
29 1.4275 1.7757 1.4276 1.7757 1.4276 1.7757 1.4276 1.7757 0.0 1.50604881284534e-06
1.427551339027571
import math as mt
def optimoSeccionAurea(f,a,b, eps, maxIter, Tipo="Max"):
    i=0
    R=(mt.sqrt(5)-1)/2
    opti=a
    while i<maxIter and b-a>eps:
        d=R*(b-a)
        x1=a+d
        x2=b-d
        i+=1
        #print(i, round(a,4), round(f(a),4), round(x2,4), round(f(x2),4), round(x1,4), round(f(x1),4), round(b,4), round(f(b),4), round(d,4), err)
        if (f(x1)>f(x2) and Tipo=="Max") or (f(x1)<f(x2) and Tipo=="Min"):
            a=x2
            opti=x1
        elif (f(x2)>f(x1) and  Tipo=="Max") or (f(x2)<f(x1) and  Tipo=="Min"):
            b=x1
            opti=x2
    return opti
optimoSeccionAurea(lambda x: 2*mt.sin(x)-x**2/10, 0, 4, 10**(-6), 2000, "Max")
1.4275518465647516
optimoSeccionAurea(lambda x: x**2, -1, 2, 10**(-6), 2000, "Min")
-2.0530310232392276e-07
import math as mt
def optimoInterpolaParbola(f,x0,x1, x2, eps, maxIter, Tipo="Max"):
    i=0
    while i<maxIter and mt.fabs(x2-x0)>eps:
        i+=1
        x3N=f(x0)*(x1**2-x2**2)+f(x1)*(x2**2-x0**2)+f(x2)*(x0**2-x1**2)
        x3D=2*f(x0)*(x1-x2)+2*f(x1)*(x2-x0)+2*f(x2)*(x0-x1)
        x3=x3N/x3D
        print(i, round(x0,4), round(f(x0),4), round(x1,4), round(f(x1),4), round(x2,4), round(f(x2),4), round(x3,4), round(f(x3),4), mt.fabs(x2-x0))
        if (f(x1)>f(x3) and Tipo=="Max") or (f(x1)<f(x3) and Tipo=="Min"):
            opti=x1
            if x3>x1:
                x2=x3
            else:
                x0=x3
        elif (f(x3)>f(x1) and  Tipo=="Max") or (f(x3)<f(x1) and  Tipo=="Min"):
            opti=x3
            if x3>x1:
                x0=x1
                x1=x3
            else:
                x2=x1
                x1=x3
    return opti
optimoInterpolaParbola(lambda x: 2*mt.sin(x)-x**2/10, 0, 1, 4, 10**(-6), 10, "Max")
#optimoInterpolaParbola(lambda x: x**2, -1, 1, 2, 10**(-6), 10, "Min")
1 0 0.0 1 1.5829 4 -3.1136 1.5055 1.7691 4.0
2 1 1.5829 1.5055 1.7691 4 -3.1136 1.4903 1.7714 3.0
3 1 1.5829 1.4903 1.7714 1.5055 1.7691 1.4256 1.7757 0.5055348739896623
4 1 1.5829 1.4256 1.7757 1.4903 1.7714 1.4266 1.7757 0.4902527508500858
5 1.4256 1.7757 1.4266 1.7757 1.4903 1.7714 1.4275 1.7757 0.06461679656582486
6 1.4266 1.7757 1.4275 1.7757 1.4903 1.7714 1.4276 1.7757 0.06365122826564096
7 1.4275 1.7757 1.4276 1.7757 1.4903 1.7714 1.4276 1.7757 0.06270443996075814
8 1.4276 1.7757 1.4276 1.7757 1.4903 1.7714 1.4276 1.7757 0.06270213484155795
9 1.4276 1.7757 1.4276 1.7757 1.4903 1.7714 1.4276 1.7757 0.06270213484155795
10 1.4276 1.7757 1.4276 1.7757 1.4903 1.7714 1.4276 1.7757 0.06270213484155795
1.4275517730931442
import math as mt
def newtonOptimo(f, x, eps):
    iter_t=0
    x_ant = x + 2*eps
    dif_1 = lambda f, x, eps: (f(x+eps)-f(x))/eps
    dif_2 = lambda f, x, eps: (f(x+eps)-2*f(x)+f(x-eps))/(eps*eps)
    while mt.fabs(x_ant-x)> eps:
        iter_t+=1
        x_ant = x
        print(x, dif_1(f, x, eps), dif_2(f, x, eps))
        if dif_2(f, x, eps)==0: return False, x
        x=x-dif_1(f, x, eps)/dif_2(f, x, eps)
    print(iter_t)
    return True, x

newtonOptimo(lambda x: 2*mt.sin(x)-x**2/10, 0.5, 10**(-5))
0.5 1.6551593294944487 -1.1588507931037382
1.9282764781663155 -1.085495261521352 -2.0735635430924044
1.4047838342406314 0.04953434635801556 -2.172504398600949
1.4275844078044477 -8.201330725654543e-05 -2.1795254490086786
1.427546778830079 -1.5543122344752192e-10 -2.1795165672244816
5
(True, 1.4275467787587646)
import math as mt
import numpy as np
def gradiente(f, x):
    eps=10**(-3)
    grad=[]
    for i in range(len(x)):
        xw=x.copy()
        xw[i]+=eps
        grad.append((f(xw)-f(x))/eps)
    return grad
def gradienteDescenso(f, x, epocas, eta):
    for i in range(epocas):
        x = x - eta*np.array(gradiente(f, x))
    return x
gradienteDescenso(lambda x: x[0]**2 + x[1]**2, [2.0,2.0], 100, 0.05)
array([-0.00044686, -0.00044686])
import math as mt
import numpy as np
def gradiente(f, x):
    eps=10**(-3)
    print([f(x.copy()) for i,ele in enumerate(x)])
    grad=[]
    # return sum([x if x!=13 and nums[idx-1 if idx >0 else 0] !=13 else 0 for idx,x in enumerate(nums)])
    for i in range(len(x)):
        xw=x.copy()
        xw[i]+=eps
        grad.append((f(xw)-f(x))/eps)
    return grad
def gradienteDescenso(f, x, epocas, eta):
    for i in range(epocas):
        x = x - eta*np.array(gradiente(f, x))
    return x
gradienteDescenso(lambda x: x[0]**2 + x[1]**2, [2.0,2.0], 100, 0.05)
[8.0, 8.0]
[6.479640005000428, 6.479640005000428]
[5.248184418050559, 5.248184418050559]
[4.250737800720911, 4.250737800720911]
[3.4428352079740168, 3.4428352079740168]
[2.788460358410025, 2.788460358410025]
[2.2584403557680557, 2.2584403557680557]
[1.829145416582518, 1.829145416582518]
[1.481435652501132, 1.481435652501132]
[1.1998079665882768, 1.1998079665882768]
[0.971705041692622, 0.971705041692622]
[0.7869556231515297, 0.7869556231515297]
[0.6373211496951956, 0.6373211496951956]
[0.5161285262013137, 0.5161285262013137]
[0.41797267117645287, 0.41797267117645287]
[0.33847558161097585, 0.33847558161097585]
[0.27409117676713207, 0.27409117676713207]
[0.22194722277739778, 0.22194722277739778]
[0.1797172925861089, 0.1797172925861089]
[0.14551705441752283, 0.14551705441752283]
[0.11782026625869117, 0.11782026625869117]
[0.09539073213198837, 0.09539073213198837]
[0.07722718734311419, 0.07722718734311419]
[0.06251865613250536, 0.06251865613250536]
[0.05060829191345405, 0.05060829191345405]
[0.04096408835141017, 0.04096408835141017]
[0.03315515577600351, 0.03315515577600351]
[0.026832505468787817, 0.026832505468787817]
[0.021713485290920723, 0.021713485290920723]
[0.017569172860728097, 0.017569172860728097]
[0.014214164314763833, 0.014214164314763833]
[0.011498303462775358, 0.011498303462775358]
[0.009299982635883053, 0.009299982635883053]
[0.007520716582996786, 0.007520716582996786]
[0.006080747515365755, 0.006080747515365755]
[0.0049154853622707766, 0.0049154853622707766]
[0.0039726245307814025, 0.0039726245307814025]
[0.0032098086185407943, 0.0032098086185407943]
[0.0025927389547651175, 0.0025927389547651175]
[0.0020936426297321117, 0.0020936426297321117]
[0.0016900316988181408, 0.0016900316988181408]
[0.001363698227904312, 0.001363698227904312]
[0.0010999003612779485, 0.0010999003612779485]
[0.0008867031096430483, 0.0008867031096430483]
[0.000714444454117989, 0.000714444454117989]
[0.0005753029496119791, 0.0005753029496119791]
[0.00046294753678447013, 0.00046294753678447013]
[0.000372253937634311, 0.000372253937634311]
[0.0002990749790387932, 0.0002990749790387932]
[0.0002400545936209236, 0.0002400545936209236]
[0.0001924771953724991, 0.0001924771953724991]
[0.00015414570533732024, 0.00015414570533732024]
[0.00012328278070026575, 0.00012328278070026575]
[9.845083580654792e-05, 9.845083580654792e-05]
[7.848728209870327e-05, 7.848728209870327e-05]
[6.245209308580913e-05, 6.245209308580913e-05]
[4.958535052677894e-05, 4.958535052677894e-05]
[3.9272873541237134e-05, 3.9272873541237134e-05]
[3.101839322149364e-05, 3.101839322149364e-05]
[2.442102759719226e-05, 2.442102759719226e-05]
[1.9157048532729904e-05, 1.9157048532729904e-05]
[1.4965123872614978e-05, 1.4965123872614978e-05]
[1.163437344181151e-05, 1.163437344181151e-05]
[8.994703282361364e-06, 8.994703282361364e-06]
[6.908984373757339e-06, 6.908984373757339e-06]
[5.266724586283616e-06, 5.266724586283616e-06]
[3.9789494340758845e-06, 3.9789494340758845e-06]
[2.9740613088690057e-06, 2.9740613088690057e-06]
[2.1944907007246795e-06, 2.1944907007246795e-06]
[1.5939884040736973e-06, 1.5939884040736973e-06]
[1.135436450137731e-06, 1.135436450137731e-06]
[7.890787831657946e-07, 7.890787831657946e-07]
[5.310915470631029e-07, 5.310915470631029e-07]
[3.4242811255004187e-07, 3.4242811255004187e-07]
[2.0788633465156954e-07, 2.0788633465156954e-07]
[1.1535553820520338e-07, 1.1535553820520338e-07]
[5.520883236990358e-08, 5.520883236990358e-08]
[1.9812916000941867e-08, 1.9812916000941867e-08]
[3.13284756395089e-09, 3.13284756395089e-09]
[4.1355356966939934e-10, 4.1355356966939934e-10]
[7.923330730014474e-09, 7.923330730014474e-09]
[2.274741499603576e-08, 2.274741499603576e-08]
[4.2621971541040604e-08, 4.2621971541040604e-08]
[6.580070580306937e-08, 6.580070580306937e-08]
[9.094778966983e-08, 9.094778966983e-08]
[1.1705200580497174e-07, 1.1705200580497174e-07]
[1.4335799125719562e-07, 1.4335799125719562e-07]
[1.693112528179801e-07, 1.693112528179801e-07]
[1.9451426669225036e-07, 1.9451426669225036e-07]
[2.1869149273944062e-07, 2.1869149273944062e-07]
[2.416615521657929e-07, 2.416615521657929e-07]
[2.633151559964537e-07, 2.633151559964537e-07]
[2.835976452250728e-07, 2.835976452250728e-07]
[3.0249522461345975e-07, 3.0249522461345975e-07]
[3.200241507199381e-07, 3.200241507199381e-07]
[3.36222278987882e-07, 3.36222278987882e-07]
[3.5114249119444334e-07, 3.5114249119444334e-07]
[3.648476185603322e-07, 3.648476185603322e-07]
[3.774065516574188e-07, 3.774065516574188e-07]
[3.8889128940370395e-07, 3.8889128940370395e-07]
array([-0.00044686, -0.00044686])