import os
import time
try:
import math
except ImportError:
import umath as math
ARCHIVO = "seno_taylor_log.txt"
# -----------------------------
# Fecha y hora formateadas
# -----------------------------
def fecha_hora():
t = time.localtime()
fecha = "{:04d}-{:02d}-{:02d}".format(t[0], t[1], t[2])
hora = "{:02d}:{:02d}:{:02d}".format(t[3], t[4], t[5])
return fecha, hora
# -----------------------------
# Asegura encabezado y obtiene próximo registro
# -----------------------------
def preparar_archivo_y_registro():
try:
os.stat(ARCHIVO)
with open(ARCHIVO, "r") as f:
lineas = f.read().splitlines()
if len(lineas) == 0:
with open(ARCHIVO, "w") as f:
f.write("nreg fecha hora x_deg sin_taylor sin_math error\n")
return 1
return len(lineas) # header incluido => nreg continua
except OSError:
with open(ARCHIVO, "w") as f:
f.write("nreg fecha hora x_deg sin_taylor sin_math error\n")
return 1
# -----------------------------
# SIN(x) por Taylor (Maclaurin)
# sin(x)= Σ (-1)^k * x^(2k+1)/(2k+1)!
# Implementación optimizada (sin factorial ni potencias costosas)
# -----------------------------
def sin_taylor(x, n_terms=10):
term = x # k=0: x
s = term
# Recurrencia:
# term_{k+1} = -term_k * x^2 / ((2k+2)(2k+3))
for k in range(n_terms - 1):
denom = (2*k + 2) * (2*k + 3)
term = -term * (x * x) / denom
s += term
return s
# -----------------------------
# Main
# -----------------------------
def main():
N = int(input("Ingrese el número maximo de ángulos (grados) a evaluar: ").strip())
if N <= 0:
print("N debe ser > 0")
return
terms = int(input("Ingrese términos de Taylor (ej. 5..12): ").strip())
if terms <= 0:
print("terms debe ser > 0")
return
nreg = preparar_archivo_y_registro()
with open(ARCHIVO, "a") as f:
for x_deg in range(1,N+1):
x_rad = math.radians(x_deg)
s_aprox = sin_taylor(x_rad, terms)
s_real = math.sin(x_rad)
err = abs(s_real - s_aprox)
fecha, hora = fecha_hora()
linea = "{} {} {} {} {:.8f} {:.8f} {:.8e}\n".format(
nreg, fecha, hora, x_deg, s_aprox, s_real, err
)
f.write(linea)
print(x_deg, s_aprox, s_real, err)
nreg += 1
time.sleep_ms(20)
print("\nDatos guardados en:", ARCHIVO)
# Ejecutar
main()