import pandas as pd #Importando librerias
import numpy as np
from math import *
import matplotlib.pyplot as plt
def biseccion(f,a,b,tol): #Comprobando si cumple el teorema de Bolzano
if f(a)*f(b) > 0:
print("Invalid interval does not satisfy Bolzano's theorem")
return
error = 1e3
X_anterior = 0
i = 1; I = []; Xa = []; Xb = []; Xm = []; #Creamos listas
Fa = []; Fb = []; E = [];Fx = []
while error > tol:
m = (a+b)/2
X_actual = m
error = (abs(X_actual-X_anterior)/X_actual) *100
I.append(i); Xa.append(a); Xb.append(b);
Xm.append(m); Fa.append(f(a)); Fb.append(f(b)); #Rellenamos las listas
E.append(error);Fx.append(f(m))
if f(a)*f(m) < 0:
b = m
else:
a = m
X_anterior = X_actual
i += 1
d = {"I":I,"F(x)":Fx,"Xa":Xa,"Xb":Xb,"Xm":Xm,"Fa":Fa,"Fb":Fb,"E %":E,}
TT = pd.DataFrame(d)
TT.set_index("I",inplace=True)
print(TT)
f = lambda x: x**2 - 2
biseccion(f,1,2,0.01)
def plotf(f,a,b,n):
x = np.linspace(a,b, num=n)
y = f(x)
fig, ax = plt.subplots()
ax.plot(x,y)
ax.grid()
ax.axhline(y=0, color='r')
ax.axvline(x=0, color='r')
plotf(f,0,2,100)
def falsapos(f,a,b,tol):
if f(a)*f(b) > 0:
print("Invalid interval does not satisfy Bolzano's theorem")
return
error = 1e3
X_anterior = 0;
i = 1; I = []; Xa = []; Xb = []; Xm = [];
Fa = []; Fb = []; Fm = []; E = [];
while error > tol:
m = a - f(a)*(b-a)/(f(b)-f(a))
X_actual = m
error = (abs(X_actual - X_anterior)/X_actual)*100
I.append(i); Xa.append(a); Xb.append(b);
Xm.append(m); Fa.append(f(a)); Fb.append(f(b));
Fm.append(f(m)); E.append(error);
if f(a)*f(m) < 0:
b = m
else:
a = m
X_anterior = X_actual
i += 1
d = {"I":I,"Xa":Xa,"Xb":Xb,"Xm":Xm,"Fa":Fa,"Fm":Fm,"Fb":Fb,"E":E}
TT = pd.DataFrame(d)
TT.set_index("I",inplace=True)
print(TT.to_string())
def puntof(f,x0,tol):
xold = x0
e = 100
a = lambda x: x
i = 1
I = []
Xr = []
Fx = []
Gx = []
Ea = []
Xr.append(x0)
Fx.append(f(x0))
Ea.append(0)
while e > tol:
xr = f(xold) + a(xold)
e = (abs(xr - xold)/xr) * 100
Gx.append(xr)
xold = xr
I.append(i)
Xr.append(xr)
Fx.append(f(xr))
Ea.append(e)
i += 1
Gx.append(f(xold) + a(xold))
d = {"Xr":Xr,"G(x)":Gx,"F(x)":Fx,"E":Ea}
TT = pd.DataFrame(d)
print(TT.to_string())
f1 = lambda x: exp(-x) - x
x0 = 0
tol = 0.1
puntof(f1,x0,tol)
def derivada(f,x0):
h=0.000000001
d=(f(x0+h)-f(x0))/h
if abs(d)<0.000001:
d=0
return(d)
def newton(f,x0,tol):
e=100
n=1;i=[];X0=[];X=[];h=[];E=[];
if derivada(f,x0)==0:
print("Enter another closest value")
else:
while e>tol:
x=x0-(f(x0))/(derivada(f,x0))
e=(abs(x-x0)/x) * 100
fa=f(x0)
i.append(n);X0.append(x0);X.append(x);
h.append(fa); E.append(e);
x0=x
n+=1
d = {"i":i,"x0":X0,"x":X,"f(x)":h,"E %":E}
TT = pd.DataFrame(d)
TT.set_index("i",inplace=True)
print(TT.to_string())
f2 = lambda x : exp(-x) - x
x0 = 0
newton(f2,x0,0.01)
# Importing NumPy Library
import numpy as np
import sys
# Reading number of unknowns
n = int(input('Enter number of unknowns: '))
# Making numpy array of n x n+1 size and initializing
# to zero for storing augmented matrix
a = np.zeros((n,n+1))
# Making numpy array of n size and initializing
# to zero for storing solution vector
x = np.zeros(n)
# Reading augmented matrix coefficients
print('Enter Augmented Matrix Coefficients:')
for i in range(n):
for j in range(n+1):
a[i][j] = int(input( 'a['+str(i)+']['+ str(j)+']='))
# Applying Gauss Elimination
for i in range(n):
if a[i][i] == 0.0:
sys.exit('Divide by zero detected!')
for j in range(i+1, n):
ratio = a[j][i]/a[i][i]
for k in range(n+1):
a[j][k] = a[j][k] - ratio * a[i][k]
# Back Substitution
x[n-1] = a[n-1][n]/a[n-1][n-1]
for i in range(n-2,-1,-1):
x[i] = a[i][n]
for j in range(i+1,n):
x[i] = x[i] - a[i][j]*x[j]
x[i] = x[i]/a[i][i]
# Displaying solution
print('\nRequired solution is: ')
for i in range(n):
print('X%d = %0.2f' %(i,x[i]), end = '\t')
import numpy as np
def diy_lu(a):
"""Construct the LU decomposition of the input matrix.
Naive LU decomposition: work column by column, accumulate elementary triangular matrices.
No pivoting.
"""
N = a.shape[0] # gives number of filas
u = a.copy() # Copy of a
L = np.eye(N) # gives a matriz of N with 1 in his diagonal
for j in range(N-1):
lam = np.eye(N) # Matriz of 1 in diagonal
gamma = u[j+1:, j] / u[j, j] # gamma = [u(1,0)/u(0,0)]
lam[j+1:, j] = -gamma
u = lam @ u
print("U", j,"\n", u,"\n")
lam[j+1:, j] = gamma
L = L @ lam
return L, u
a = np.array([[10,2,-1],
[-3,-6,2],
[1,1,5]])
l, u = diy_lu(a)
print("este es L","\n",l,"\n")
print("este es U","\n",u,"\n")
# Gauss Seidel Iteration
# Defining equations to be solved
# in diagonally dominant form
f1 = lambda x,y,z: (7.85 + 0.1*y+0.2*z)/3
f2 = lambda x,y,z: (-19.3-0.1*x+0.3*z)/7
f3 = lambda x,y,z: (71.4-0.3*x+0.2*y)/10
# Initial setup
x0 = 0
y0 = 0
z0 = 0
count = 1
# Reading tolerable error
e = float(input('Enter tolerable error: '))
# Implementation of Gauss Seidel Iteration
print('\nCount\tx\ty\tz\n')
condition = True
while condition:
x1 = f1(x0,y0,z0)
y1 = f2(x1,y0,z0)
z1 = f3(x1,y1,z0)
print('%d\t%0.4f\t%0.4f\t%0.4f\n' %(count, x1,y1,z1))
e1 = abs(x0-x1);
e2 = abs(y0-y1);
e3 = abs(z0-z1);
count += 1
x0 = x1
y0 = y1
z0 = z1
condition = e1>e and e2>e and e3>e
print('\nSolution: x=%0.3f, y=%0.3f and z = %0.3f\n'% (x1,y1,z1))