Professional Documents
Culture Documents
#fonction inverse
def inv_diag(D::Matrix{Float64}):
import numpy as np
from numpy.linalg import *
Returns 3 variables:
1. x, the estimated solution
2. rel_diff, the relative difference between last 2
iterations for x
3. k, the number of iterations used. If k=maxiter,
then the required tolerance was not met.
"""
n = A.shape[0]
x = x0.copy()
x_prev = x0.copy()
k = 0
rel_diff = tol * 2
return x, rel_diff, k
tol = 1E-9
maxiter = 200
x, rel_diff, k = jacobi(A, b, x0, tol, maxiter)
if k == maxiter:
print(('WARNING: the Jacobi iterations did not '
'converge within the required tolerance.'))
print(('The solution is %s; within a tolerance of %g, '
'using %d iterations.' % (x, rel_diff, k)))
print('Solution error = norm(Ax-b) = %g' % \
norm(np.dot(A,x)-b))
print('Condition number of A = %0.5f' % cond(A))
print('Solution from built-in functions = %s' % solve(A, b))
#LIANTSOA
def jacobi(A,b,Imax,eps,x0):
D=np.diag(np.diag(A))
N=D-A
r=A*x0-b
x=x0
i=0
while ((i<Imax) and ((la.norm(r))<eps)):
x=(la.inv(D))*N*x+(la.inv(D))*b
r=A*x-b
i=i+1
return x
A=np.array([[1,2,3],[4,5,6],[7,8,9]])
x0=np.array([[1],[1],[1]])
b=np.array([[3],[6],[7]])
print(jacobi(A,b,1000,10**(-3),x0))
using LinearAlgebra
function extraire_mat(A::Matrix{Float64})
E = tril(A,-1)
F = tril(A,-1)
D = diag(A)
return (E,D,F)
end
# Fonction inverse
function inv_diag(D::Matrix{Float64})
nbrows, nbcols = size(D)
inverse = Zeros(Float64,nbrows, nbrows)
for i=1:nbrows
inverse[i] = 1/D[i,i]
end
return inverse
end
jacobi(A,b,x0)
using LinearAlgebra
using Plots
function u(x)
return -sin(2*pi*x)
end
function f(x)
return 4*pi^2*sin(2*pi*x)
end
function calcul_sol_exact(N)
x = [k/N for k in 0:N]
sol_exact = u.(x)
return x, sol_exact
end
function calcul_A(N)
d = [1 for k in 1:N-2]
D = [-2 for k in 1:N-1]
return Tridiagonal(d,D,d)
end
function calcul_f(N)
return [f(k/N) for k in 1:N-1]
end
function calcul_v(N)
A = calcul_A(N)
v = A\calcul_f(N)
v = 1/(N^2) * v
return v
end
function calcul_erreur_approx(N)
v = vcat([0],calcul_v_Thomas(N),[0])
x, sol_exact = calcul_sol_exact(N)
erreur_approx = max(abs.(v-sol_exact)...)
return erreur_approx
end
#On trace les valeurs de u(x_k) et des solutions approchées v_k pour N=10.
#On peut rajouter l'argument seriestype = :scatter dans la fonction plot pour
n'afficher que les points.
N = 10;
x, sol_exact = calcul_sol_exact(N);
v = vcat([0],calcul_v_Thomas(N),[0]);
p = plot(x, sol_exact, label = "Solution exacte", ylabel = "y", xlabel = "x",
color=:red, title = "N = 10")
plot!(p, x, v, color=:green, label="Solution approchée")
#=
Anne-CAtherine Letournel
09/03/2021
TP1 Calcul scientifique: méthode de Newton
=#
# script de test
# initialisation des variables d'entrée
x0 = -2.5
f = x -> x^3 -4*x + 1
df = x -> 3*x^2 - 4
tol = 1e-6
itmax = 100
x0 = 0.0
x0 = 2.0
# script de test
# initialisation des variables d'entrée
x0 = -2.5
a = 1
b = 0
c = -4
d = 1
tol = 1e-6
itmax = 100