Método de la bisección y newton.

Método de la Bisección

Fundamentación Teórica

Teorema del Valor Intermedio

Sea \(f:[a,b]\to\mathbb{R}\) continua tal que

\[ f(a)f(b) < 0, \]

entonces existe \(c \in (a,b)\) tal que

\[ f(c)=0. \]


Idea del Método

  1. Calcular el punto medio:

\[ c = \frac{a+b}{2} \]

  1. Evaluar \(f(c)\).

  2. Reducir el intervalo:

\[ \begin{cases} [a,c] & \text{si } f(a)f(c) < 0 \\ [c,b] & \text{si } f(c)f(b) < 0 \end{cases} \]


Fórmula Iterativa

\[ c_n = \frac{a_n + b_n}{2} \]


Análisis del Error

La longitud del intervalo en la iteración \(n\) es

\[ b_n - a_n = \frac{b_0 - a_0}{2^n} \]

y el error satisface

\[ |r - c_n| \le \frac{b_0 - a_0}{2^{n+1}}. \]

El método tiene convergencia lineal.

# naombre <- function(parámetros){función evaluada en # los parámetros}
f <- function(x) {x^3 - x - 2}

a <- 1
b <- 2

# Entre más pequeÑo es el intervalo más rápido será la conver
tol <- 1e-6
#tol
#0.000001
max_iter <- 100

if (f(a) * f(b) >= 0) {
  stop("El intervalo no cumple f(a)f(b) < 0")
}

for (i in 1:max_iter) {
  c <- (a + b) / 2
  
  if (abs(f(c)) < tol || (b - a)/2 < tol) {
    break
  }
  
  if (f(a) * f(c) < 0) {
    b <- c
  } else {
    a <- c
  }
}

c
## [1] 1.52138
f(1)
## [1] -2
f(2)
## [1] 4
f(0)
## [1] -2
f(5)
## [1] 118
library(ggplot2)
## Warning: package 'ggplot2' was built under R version 4.4.3
f <- function(x) x^3 - x - 2

a <- 1
b <- 2
tol <- 1e-6
max_iter <- 100

for (i in 1:max_iter) {
  c <- (a + b) / 2
  if (abs(f(c)) < tol || (b - a)/2 < tol) break
  if (f(a) * f(c) < 0) {
    b <- c
  } else {
    a <- c
  }
}

aprox <- c
real <- uniroot(f, c(1,2))$root

x_vals <- seq(0, 2.5, length.out = 4000)
df <- data.frame(x = x_vals, y = f(x_vals))
# ggplot2 data mapping y geometría
p <- ggplot(df, aes(x, y)) +
  geom_line() +
  geom_hline(yintercept = 0) +
  geom_point(aes(x = aprox, y = 0)) +
  geom_point(aes(x = real, y = 0)) +
  labs(title = "Metodo de Biseccion",
       subtitle = paste("Aprox =", round(aprox,6),
                        "Real =", round(real,6)),
       x = "x",
       y = "f(x)")

print(p)
## Warning in geom_point(aes(x = aprox, y = 0)): All aesthetics have length 1, but the data has 4000 rows.
## ℹ Please consider using `annotate()` or provide this layer with data containing
##   a single row.
## Warning in geom_point(aes(x = real, y = 0)): All aesthetics have length 1, but the data has 4000 rows.
## ℹ Please consider using `annotate()` or provide this layer with data containing
##   a single row.

library(ggplot2)

f <- function(x) cos(x) - x

a <- 0
b <- 1
tol <- 1e-8
max_iter <- 100

for (i in 1:max_iter) {
  c <- (a + b) / 2
  if (abs(f(c)) < tol || (b - a)/2 < tol) break
  if (f(a) * f(c) < 0) {
    b <- c
  } else {
    a <- c
  }
}

aprox <- c
real <- uniroot(f, c(0,1))$root

x_vals <- seq(-1, 2, length.out = 600)
df <- data.frame(x = x_vals, y = f(x_vals))

p <- ggplot(df, aes(x, y)) +
  geom_line(color = "#2C3E50", linewidth = 1.2) +
  geom_hline(yintercept = 0, color = "black", linewidth = 0.8) +
  geom_vline(xintercept = aprox, color = "#E74C3C", linetype = "dashed", linewidth = 1) +
  geom_vline(xintercept = real, color = "#27AE60", linetype = "dotted", linewidth = 1) +
  geom_point(aes(x = aprox, y = 0), color = "#E74C3C", size = 3) +
  geom_point(aes(x = real, y = 0), color = "#27AE60", size = 3) +
  labs(
    title = "Método de Bisección",
    subtitle = paste("Aprox =", round(aprox,8),
                     "| Raíz real =", round(real,8)),
    x = "x",
    y = "f(x) = cos(x) - x"
  ) +
  theme_minimal(base_size = 14) +
  theme(
    plot.title = element_text(face = "bold"),
    plot.subtitle = element_text(face = "italic")
  )

print(p)
## Warning in geom_point(aes(x = aprox, y = 0), color = "#E74C3C", size = 3): All aesthetics have length 1, but the data has 600 rows.
## ℹ Please consider using `annotate()` or provide this layer with data containing
##   a single row.
## Warning in geom_point(aes(x = real, y = 0), color = "#27AE60", size = 3): All aesthetics have length 1, but the data has 600 rows.
## ℹ Please consider using `annotate()` or provide this layer with data containing
##   a single row.

f(0)
## [1] 1
f(1)
## [1] -0.4596977

Método delta : Método de simulación y aproximación estadístico

Método de la Secante

Fundamentación Teórica

El método de la secante es un método iterativo para aproximar raíces de una función
\(f(x)\), basado en una aproximación lineal usando diferencias finitas.

A diferencia del método de Newton, no requiere calcular la derivada.


Idea Geométrica

Dados dos puntos iniciales \(x_0\) y \(x_1\), se construye la recta secante que pasa por

\[ (x_0, f(x_0)) \quad \text{y} \quad (x_1, f(x_1)). \]

La ecuación de la recta secante es

\[ y - f(x_1) = \frac{f(x_1)-f(x_0)}{x_1-x_0}(x - x_1). \]

La siguiente aproximación \(x_2\) se obtiene imponiendo \(y=0\):

\[ x_{2} = x_1 - f(x_1)\frac{x_1 - x_0}{f(x_1)-f(x_0)}. \]


Fórmula Iterativa General

Para \(n \ge 1\):

\[ x_{n+1} = x_n - f(x_n) \frac{x_n - x_{n-1}} {f(x_n)-f(x_{n-1})}. \]


Interpretación Analítica

El método puede verse como una versión del método de Newton donde la derivada

\[ f'(x_n) \]

se aproxima mediante el cociente incremental:

\[ f'(x_n) \approx \frac{f(x_n)-f(x_{n-1})}{x_n-x_{n-1}}. \]


Orden de Convergencia

Si \(f\) es suficientemente suave y la raíz \(r\) es simple, el método tiene

\[ p = \frac{1+\sqrt{5}}{2} \approx 1.618, \]

es decir, convergencia superlineal.


Criterio de Parada

Se detiene cuando

\[ |x_{n+1} - x_n| < \varepsilon \]

o bien

\[ |f(x_n)| < \varepsilon. \]


Ventajas y Desventajas

Ventajas - No requiere derivada. - Convergencia más rápida que bisección.

Desventajas - No garantiza convergencia global. - Puede fallar si \(f(x_n)-f(x_{n-1})\) es cercano a cero.

Método Delta (Método Delta Estadístico)

Fundamentación Teórica

El método delta es una técnica para aproximar la distribución de una función de un estimador, usando una expansión de Taylor de primer orden.

Sea \(X_n\) un estimador tal que

\[ \sqrt{n}(X_n - \theta) \;\xrightarrow{d}\; \mathcal{N}(0,\sigma^2). \]

Sea \(g\) una función diferenciable en \(\theta\) con \(g'(\theta)\neq 0\).

Entonces,

\[ \sqrt{n}\big(g(X_n) - g(\theta)\big) \;\xrightarrow{d}\; \mathcal{N}\!\left(0,\; \sigma^2 \,[g'(\theta)]^2\right). \]


Idea de la Demostración

Se usa la expansión de Taylor de primer orden alrededor de \(\theta\):

\[ g(X_n) = g(\theta) + g'(\theta)(X_n - \theta) + R_n, \]

donde el residuo satisface

\[ R_n = o_p(X_n - \theta). \]

Multiplicando por \(\sqrt{n}\):

\[ \sqrt{n}\big(g(X_n)-g(\theta)\big) = g'(\theta)\sqrt{n}(X_n-\theta) + \sqrt{n}R_n. \]

Como

\[ \sqrt{n}R_n \xrightarrow{p} 0, \]

y por Slutsky:

\[ \sqrt{n}\big(g(X_n)-g(\theta)\big) \;\xrightarrow{d}\; \mathcal{N}\!\left(0,\sigma^2[g'(\theta)]^2\right). \]


Versión Multivariada

Si

\[ \sqrt{n}(X_n-\theta) \xrightarrow{d} \mathcal{N}(0,\Sigma), \]

y \(g:\mathbb{R}^k\to\mathbb{R}\) es diferenciable, entonces

\[ \sqrt{n}\big(g(X_n)-g(\theta)\big) \xrightarrow{d} \mathcal{N}\!\left( 0, \nabla g(\theta)^T \Sigma \nabla g(\theta) \right). \]


Interpretación

El método delta permite aproximar:

  • Varianza de funciones de estimadores.
  • Intervalos de confianza transformados.
  • Distribuciones asintóticas no lineales.

Es una herramienta central en inferencia asintótica.

Ley de los grandes números

set.seed(123)

n <- 1000
x <- rnorm(n, mean = 5, sd = 2)

media_acumulada <- cumsum(x) / seq_along(x)

plot(
  media_acumulada,
  type = "l",
  lwd = 2,
  col = "blue",
  xlab = "n",
  ylab = "Media muestral",
  main = "Ley de los Grandes Números"
) 

Teorema del límite central

Teorema del Límite Central (Enunciado Matemático)

Sea \(\{X_i\}_{i=1}^\infty\) una sucesión de variables aleatorias independientes e idénticamente distribuidas (i.i.d.) tales que

\[ \mathbb{E}(X_i) = \mu \quad \text{y} \quad \mathrm{Var}(X_i) = \sigma^2 < \infty. \]

Definimos la media muestral

\[ \overline{X}_n = \frac{1}{n}\sum_{i=1}^n X_i. \]

Entonces,

\[ \sqrt{n} \left( \overline{X}_n - \mu \right) \xrightarrow{d} \mathcal{N}(0,\sigma^2). \]

Equivalentemente,

\[ \frac{ \overline{X}_n - \mu }{ \sigma/\sqrt{n} } \xrightarrow{d} \mathcal{N}(0,1). \]


Interpretación

Para \(n\) grande,

\[ \overline{X}_n \approx \mathcal{N} \left( \mu, \frac{\sigma^2}{n} \right). \]

Esto significa que la distribución de la media muestral se aproxima a una normal, independientemente de la distribución original de \(X_i\), siempre que tenga varianza finita.

library(ggplot2)

set.seed(123)

n <- 40
m <- 10000

shape <- 2
scale <- 1

medias <- replicate(m, mean(rweibull(n, shape = shape, scale = scale)))

df <- data.frame(medias = medias)

mu <- scale * gamma(1 + 1/shape)
varianza <- scale^2 * (gamma(1 + 2/shape) - (gamma(1 + 1/shape))^2)
sd_media <- sqrt(varianza / n)

ggplot(df, aes(x = medias)) +
  geom_histogram(aes(y = ..density..), bins = 40,
                 fill = "lightblue", color = "white") +
  stat_function(fun = dnorm,
                args = list(mean = mu, sd = sd_media),
                color = "red", linewidth = 1.2) +
  labs(title = "TLC con Distribución Weibull",
       subtitle = paste("n =", n, "| shape =", shape, "| scale =", scale),
       x = "Medias muestrales",
       y = "Densidad") +
  theme_minimal(base_size = 14)
## Warning: The dot-dot notation (`..density..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(density)` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

library(ggplot2)

x <- seq(0, 4, length.out = 500)

df <- rbind(
  data.frame(x = x, y = dweibull(x, shape = 0.8, scale = 1), grupo = "shape=0.8, scale=1"),
  data.frame(x = x, y = dweibull(x, shape = 1.5, scale = 1), grupo = "shape=1.5, scale=1"),
  data.frame(x = x, y = dweibull(x, shape = 2.5, scale = 1), grupo = "shape=2.5, scale=1"),
  data.frame(x = x, y = dweibull(x, shape = 2, scale = 2), grupo = "shape=2, scale=2")
)

ggplot(df, aes(x = x, y = y, color = grupo)) +
  geom_line(linewidth = 1.2) +
  labs(
    title = "Distribuciones Weibull con Diferentes Parámetros",
    x = "x",
    y = "Densidad",
    color = "Parámetros"
  ) +
  theme_minimal(base_size = 14)

Teorema del Límite Central

Enunciado

Sea \(X_1, X_2, \dots, X_n\) una sucesión de variables aleatorias i.i.d. tales que

\[ \mathbb{E}(X_i) = \mu \quad \text{y} \quad \mathrm{Var}(X_i) = \sigma^2 < \infty. \]

Definimos la suma centrada y estandarizada:

\[ Z_n = \frac{\sum_{i=1}^n (X_i - \mu)}{\sigma \sqrt{n}}. \]

Entonces,

\[ Z_n \xrightarrow{d} \mathcal{N}(0,1). \]


Demostración (usando funciones características)

Sea \(\varphi_X(t)\) la función característica de \(X_i\):

\[ \varphi_X(t) = \mathbb{E}(e^{itX}). \]

Como \(X_i\) tiene media \(\mu\) y varianza \(\sigma^2\), su expansión de Taylor alrededor de \(t=0\) es:

\[ \varphi_X(t) = 1 + it\mu - \frac{t^2\sigma^2}{2} + o(t^2). \]

Para la variable centrada \(Y_i = X_i - \mu\):

\[ \varphi_Y(t) = 1 - \frac{t^2\sigma^2}{2} + o(t^2). \]

Ahora consideramos

\[ Z_n = \frac{1}{\sigma\sqrt{n}}\sum_{i=1}^n Y_i. \]

Por independencia:

\[ \varphi_{Z_n}(t) = \left[ \varphi_Y\left(\frac{t}{\sigma\sqrt{n}}\right) \right]^n. \]

Sustituyendo la expansión:

\[ \varphi_Y\left(\frac{t}{\sigma\sqrt{n}}\right) = 1 - \frac{t^2}{2n} + o\left(\frac{1}{n}\right). \]

Entonces:

\[ \varphi_{Z_n}(t) = \left(1 - \frac{t^2}{2n} + o\left(\frac{1}{n}\right)\right)^n. \]

Tomando límite cuando \(n \to \infty\):

\[ \lim_{n\to\infty} \varphi_{Z_n}(t) = e^{-t^2/2}. \]

Pero

\[ e^{-t^2/2} \]

es la función característica de la normal estándar \(\mathcal{N}(0,1)\).

Por el Teorema de Lévy,

\[ Z_n \xrightarrow{d} \mathcal{N}(0,1). \]

Demostración usando MGF

Sea \(M_X(t)=\mathbb{E}(e^{tX})\) la función generadora de momentos de \(X_i\).

Por expansión de Taylor alrededor de \(t=0\):

\[ M_X(t) = 1 + \mu t + \frac{\sigma^2+\mu^2}{2}t^2 + o(t^2). \]

Definimos la variable centrada

\[ Y_i = X_i - \mu. \]

Su MGF es

\[ M_Y(t) = \mathbb{E}(e^{tY}) = e^{-\mu t} M_X(t). \]

Al expandir:

\[ M_Y(t) = 1 + \frac{\sigma^2}{2}t^2 + o(t^2). \]


MGF de la suma estandarizada

Sea

\[ S_n=\sum_{i=1}^n Y_i. \]

Por independencia:

\[ M_{S_n}(t) = \left[M_Y(t)\right]^n. \]

Para

\[ Z_n=\frac{S_n}{\sigma\sqrt{n}}, \]

tenemos

\[ M_{Z_n}(t) = \left[ M_Y\!\left(\frac{t}{\sigma\sqrt{n}}\right) \right]^n. \]

Sustituyendo la expansión:

\[ M_Y\!\left(\frac{t}{\sigma\sqrt{n}}\right) = 1 + \frac{t^2}{2n} + o\!\left(\frac{1}{n}\right). \]

Entonces

\[ M_{Z_n}(t) = \left( 1 + \frac{t^2}{2n} + o\!\left(\frac{1}{n}\right) \right)^n. \]


Paso al límite

Tomando límite cuando \(n \to \infty\):

\[ \lim_{n\to\infty} M_{Z_n}(t) = e^{t^2/2}. \]

Pero

\[ e^{t^2/2} \]

es la MGF de la normal estándar \(\mathcal{N}(0,1)\).

Por unicidad de la función generadora de momentos,

\[ Z_n \xrightarrow{d} \mathcal{N}(0,1). \] # Estimación de \(\beta_0\) y \(\beta_1\)
## Modelo de Regresión Lineal Simple

Modelo

Sea el modelo

\[ Y_i = \beta_0 + \beta_1 X_i + \varepsilon_i, \qquad i=1,\dots,n, \]

donde

\[ \mathbb{E}(\varepsilon_i)=0, \qquad \mathrm{Var}(\varepsilon_i)=\sigma^2. \]


Estimadores por Mínimos Cuadrados

Se minimiza la suma de cuadrados:

\[ S(\beta_0,\beta_1) = \sum_{i=1}^n \left( Y_i - \beta_0 - \beta_1 X_i \right)^2. \]


Derivadas Normales

Derivando e igualando a cero:

\[ \frac{\partial S}{\partial \beta_0}=0, \qquad \frac{\partial S}{\partial \beta_1}=0. \]

Se obtienen las ecuaciones normales:

\[ \sum Y_i = n\beta_0 + \beta_1 \sum X_i \]

\[ \sum X_i Y_i = \beta_0 \sum X_i + \beta_1 \sum X_i^2 \]


Solución

Definiendo

\[ \bar X = \frac{1}{n}\sum X_i, \qquad \bar Y = \frac{1}{n}\sum Y_i, \]

el estimador de la pendiente es

\[ \hat{\beta}_1 = \frac{ \sum (X_i-\bar X)(Y_i-\bar Y) }{ \sum (X_i-\bar X)^2 }. \]

Equivalentemente,

\[ \hat{\beta}_1 = \frac{S_{XY}}{S_{XX}}. \]


El intercepto es

\[ \hat{\beta}_0 = \bar Y - \hat{\beta}_1 \bar X. \]


Forma Alternativa

\[ \hat{\beta}_1 = \frac{ n\sum X_i Y_i - \sum X_i \sum Y_i }{ n\sum X_i^2 - (\sum X_i)^2 } \]

\[ \hat{\beta}_0 = \frac{\sum Y_i - \hat{\beta}_1 \sum X_i}{n}. \]

Función lineal model

data("mtcars")
View(mtcars)
data(mtcars)
# LM EXPLICADA - EXPLICATIVAS - DATA
modelo <- lm(mpg ~ wt, data = mtcars)

summary(modelo)
## 
## Call:
## lm(formula = mpg ~ wt, data = mtcars)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -4.5432 -2.3647 -0.1252  1.4096  6.8727 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  37.2851     1.8776  19.858  < 2e-16 ***
## wt           -5.3445     0.5591  -9.559 1.29e-10 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 3.046 on 30 degrees of freedom
## Multiple R-squared:  0.7528, Adjusted R-squared:  0.7446 
## F-statistic: 91.38 on 1 and 30 DF,  p-value: 1.294e-10
plot(
  mtcars$wt,
  mtcars$mpg,
  pch = 19,
  col = "steelblue",
  xlab = "Peso (wt)",
  ylab = "Millas por galón (mpg)",
  main = "Regresión Lineal Simple"
)

abline(modelo, col = "red", lwd = 2)