Introduccion a Python
Introduccion a Python
python
Copiar código
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
python
Copiar código
ax.set_title('Título del gráfico')
ax.set_xlabel('Etiqueta del eje x')
ax.set_ylabel('Etiqueta del eje y')
python
Copiar código
plt.plot(x, y, linestyle='--') # Línea discontinua
plt.plot(x, y, linestyle=':') # Línea de puntos
python
Copiar código
plt.plot(x, y, color='red') # Usando un nombre de color
plt.plot(x, y, color='#FF0000') # Usando un código
hexadecimal
python
Copiar código
plt.plot(x, y, marker='o') # Marcadores en forma de círculo
10. ¿Qué función en Matplotlib permite guardar un gráfico
de línea como un archivo de imagen? ¿Cuáles son los
formatos soportados?
python
Copiar código
plt.savefig('grafico.png')
python
Copiar código
plt.plot(x1, y1, label='Línea 1')
plt.plot(x2, y2, label='Línea 2')
plt.legend()
plt.show()
python
Copiar código
fig, ax1 = plt.subplots()
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b-')
python
Copiar código
plt.xlim(0, 10) # Ajusta el límite del eje X de 0 a 10
plt.ylim(-5, 5) # Ajusta el límite del eje Y de -5 a 5
python
Copiar código
plt.annotate('Anotación', xy=(x, y), xytext=(x + 1, y + 1),
arrowprops=dict(facecolor='black', shrink=0.05))
python
Copiar código
from scipy.interpolate import make_interp_spline
import numpy as np
import matplotlib.pyplot as plt
plt.plot(xnew, ynew)
plt.show()
PARTE PRACTICA
1-
import numpy as np
h = 1.0
nueva_h = h / 2
break
h = nueva_h
derivada_estimada = nueva_derivada
return derivada_estimada
f = np.poly1d(coef)
xo = 1.5
precision = 1e-6
import numpy as np
h = (b - a) / n
suma += f(a + i * h)
return h * suma
f = np.poly1d(coef)
a, b = 0, 3
n = 1000
resultado = integral_trapecio(f, a, b, n)
import numpy as np
x = xo
for i in range(max_iter):
fx = f(x)
dfx = df(x)
return x
return x
f = np.poly1d(coef)
df = f.deriv()
xo = 2.5
import numpy as np
for _ in range(max_iter):
c = (a + b) / 2
return c
b=c
else:
a=c
return c
f = np.poly1d(coef)
a, b = 0, 3
raiz = biseccion(f, a, b)
import numpy as np
def dft(x):
N = len(x)
X = np.zeros(N, dtype=complex)
for k in range(N):
for n in range(N):
return X
# Aplicar la DFT
resultado_dft = dft(datos)
import numpy as np
if A.shape[1] != B.shape[0]:
for i in range(A.shape[0]):
for j in range(B.shape[1]):
for k in range(A.shape[1]):
return result
7-
import numpy as np
def LU_decomposition(A):
n = A.shape[0]
# Inicializar matrices L y U
L = np.eye(n)
U = A.copy()
for i in range(n):
if U[i, i] == 0:
L[j, i] = factor
return L, U
# Ejemplo
L, U = LU_decomposition(A)
print("L:\n", L)
print("U:\n", U)
8-
import numpy as np
n = len(b)
x = np.zeros(n)
for it in range(max_iter):
x_new = np.copy(x)
for i in range(n):
# Verificar la convergencia
return x_new
x = x_new
import numpy as np
def determinant(A):
n = A.shape[0]
if n == 2:
det = 0
for c in range(n):
det += cofactor
return det
10-
import numpy as np
def gauss_jordan_inverse(A):
n = A.shape[0]
I = np.eye(n)
for i in range(n):
if augmented_matrix[i, i] == 0:
# Normalizar la fila i
augmented_matrix[i] /= augmented_matrix[i, i]
for j in range(n):
if i != j:
augmented_matrix[j] -= augmented_matrix[j, i] *
augmented_matrix[i]
return inverse
11-
import numpy as np
sine = 0
for n in range(terms):
sine += term
break
return sine
cosine = 0
for n in range(terms):
cosine += term
break
return cosine
x = np.pi / 3 # 60 grados
import numpy as np
def verify_trig_identity(x):
seno = np.sin(x)
cos = np.cos(x)
if np.isclose(identity, 1):
else:
x = np.pi / 4 # 45 grados
verify_trig_identity(x)
13-
import numpy as np
def plot_trig_functions(resolution=1000):
sine = np.sin(x)
cosine = np.cos(x)
plt.xlabel('x')
plt.ylabel('y')
plt.axhline(0, color='black',linewidth=0.5)
plt.axvline(0, color='black',linewidth=0.5)
plt.legend()
plt.grid(True)
plt.show()
plot_trig_functions()
14-
import math
r = math.sqrt(x**2 + y**2)
teta_deg = math.degrees(teta)
return r, teta_deg
theta = math.radians(theta_deg)
x = r * math.cos(theta)
y = r * math.sin(theta)
return x, y
15-
import math
if a and A and B:
b = a * math.sin(math.radians(B)) / math.sin(math.radians(A))
return b
c = a * math.sin(math.radians(C)) / math.sin(math.radians(A))
return c
else:
return None
if a and b and C:
return c
return C
else:
return None
16-
import numpy as np
w = 2 * np.pi * f
H=1/Z
# Frecuencia resonante
plt.plot(f, H)
plt.xlabel('Frecuencia (Hz)')
plt.ylabel('Respuesta |H(f)|')
plt.legend()
plt.grid(True)
plt.show()
17-
P = V * I * math.cos(math.radians(phi))
Q = V * I * math.sin(math.radians(phi))
S=V*I
import numpy as np
filtered_signal = np.convolve(signal,
np.ones(window_size)/window_size, mode='valid')
return filtered_signal
window_size = 100
else:
window_size = 50
return filtered_signal
# Señal de ejemplo
t = np.linspace(0, 1, 500)
# Filtro
plt.show()
19-
import numpy as np
N = len(signal)
T = 1 / sample_rate
yf = np.fft.fft(signal)
xf = np.fft.fftfreq(N, T)[:N//2]
# Ejemplo de señal
sample_rate = 1000
plt.plot(xf, yf)
plt.grid()
plt.show()
20-
import numpy as np
charge = np.zeros(len(t))
current = np.zeros(len(t))
charge[0] = initial_charge
current[0] = initial_current
L = 0.001 # Henrys
C = 0.01 # Farads
initial_charge = 1 # Coulombs
initial_current = 0 # Amperes
dt = 0.001
t_max = 1
# Simulación
plt.legend()
plt.xlabel("Tiempo (s)")
plt.ylabel("Amplitud")
plt.grid(True)
plt.show()
21-
import numpy as np
vx0 = v0 * np.cos(theta)
vy0 = v0 * np.sin(theta)
t_max = 2 * vy0 / g
# Tiempo de simulación
# Trayectoria
x = vx0 * t
y = np.maximum(0, y)
# Graficar
plt.plot(x, y)
plt.ylabel('Altura (m)')
plt.grid(True)
plt.show()
22-
import math
masa = 5.0 # kg
altura = 20.0 # m
# Cálculo de energías
if velocidad > 0:
Ec = energia_cinetica(masa, velocidad)
else:
Ec = 0
if altura > 0:
Ep = energia_potencial(masa, altura)
else:
Ep = 0
23-
import math
# Constante de Coulomb
k = 8.99e9 # Nm²/C²
q1 = 1e-6 # Carga 1 en C
q2 = -1e-6 # Carga 2 en C
# Cálculo de la fuerza
if q1 == q2:
else:
import numpy as np
# Ciclo de simulación
plt.plot(t, theta)
plt.xlabel('Tiempo (s)')
plt.ylabel('Ángulo (radianes)')
plt.grid(True)
plt.show()
25-
import math
masa_tierra = 5.972e24 # kg
radio_tierra = 6.371e6 # m
else:
def es_primo(n):
if n < 2:
return False
if n % i == 0:
return False
return True
def primos_en_rango(rango):
# Rango dado
primos = primos_en_rango(rango)
def fibonacci(n):
serie = [0, 1]
serie.append(serie[-1] + serie[-2])
return serie[:n]
serie_fib = fibonacci(n)
def ordenamiento_burbuja(lista):
n = len(lista)
for i in range(n):
ordenado = True
ordenado = False
if ordenado:
break
return lista
# Lista desordenada
lista_ordenada = ordenamiento_burbuja(lista)
def descomponer_en_factores(n):
factores = []
divisor = 2
while n > 1:
while n % divisor == 0:
factores.append(divisor)
n //= divisor
divisor += 1
return factores
n = 56
factores_primos = descomponer_en_factores(n)
while b != 0:
a, b = b, a % b
return a
a, b = 48, 18
resultado_mcd = mcd(a, b)