Como se comporta el error relativo en los cálculos numéricos (operaciones elementales)
f = function(x) (1-x)^6
ef = function(x) x^6-6*x^5+15*x^4-20* x^3+15* x^2-6* x+1
options(scipen = 999)
x = seq(0.995, 1.005, by=0.0001)
y1 = f(x)
y2 = ef(x)
head((y1-y2),10)
[1] 0.0000000000000005259669 0.0000000000000022949677
[3] -0.0000000000000002039074 -0.0000000000000016552825
[5] -0.0000000000000002956657 0.0000000000000003101598
[7] -0.0000000000000007372919 -0.0000000000000007840643
[9] -0.0000000000000016163956 0.0000000000000011973906
Graficamente se puede apreciar el error
x = seq(0.995, 1.005, by=0.0001)
a = x[1]; b = x[length(x)]
curve((1-x)^6, a, b, col="blue"); abline(h=0,v=0, lty=3)
curve(x^6-6*x^5+15*x^4-20* x^3+15* x^2-6* x+1, a, b, col="red", add=T)
Problema: Encuentre una formula iterativa,para calcular la raíz real n-esima de un número real.
Solución: para la solución de este problema hay que tener en cuenta dos casos: - n par (número real positivo)
- n impar
Fx <- function(x,n,v) x-(x^n-v)/(n*x^(n-1))
Gx <- function(x,n,v) x^n-v
Hx <- function(x,n) n*x^(n-1)
calcularRaiz <- function(v,n)
{
options(scipen = 0)
options(digits = 10)
x <- v/2
error <- 1
i <- 0
while(error > 1.e-6)
{
x <- Fx(x,n,v)
error <- abs(Gx(x,n,v))/Hx(x,n)
cat(" x= ",x," \terror= ",error,"\n")
i <- i + 1
}
}
calcularRaiz(7,2)
x= 2.75 error= 0.1022727273
x= 2.647727273 error= 0.001975224346
x= 2.645752048 error= 7.373161104e-07
calcularRaiz(120,3)
x= 40.01111111 error= 13.31205092
x= 26.69906019 error= 8.843573142
x= 17.85548705 error= 5.82636575
x= 12.0291213 error= 3.733272638
x= 8.295848661 error= 2.184065831
x= 6.111782829 error= 0.9664219837
x= 5.145360845 error= 0.2042460419
x= 4.941114804 error= 0.008675378334
x= 4.932439425 error= 1.527650565e-05
x= 4.932424149 error= 4.731361971e-11
raizCuadrada <- function(n, e, x)
Warning messages:
1: In readChar(file, size, TRUE) : truncating string with embedded nuls
2: In scan(file = file, what = what, sep = sep, quote = quote, dec = dec, :
EOF within quoted string
{
eActual <- c()
eAnterior <- c()
k <- 0
y <- (1/2)*(x+(n/x))
k <- abs(x-y)
while(k > e){
x <- y
y <- (1/2)*(x+(n/x))
eAnterior <- c(eAnterior, k)
k <- abs(x-y)
eActual <- c(eActual, k)
}
#cat(" x= ",x," \terror= ",error,"\n")
#cat("Iteraciones =",y"," \tk= ",k,"\n")
# Inserción de puntos y líneas en la gráfica
points(eActual, eAnterior, col = "red")
lines(eActual, eAnterior, col = "blue")
return(cat("El resultado es: ", y, " con error de ", e))
}
f = function(x) (x)
{
plot(f, xlim=c(0,60), ylim=c(0,60),
col = "white", xlab="Error actual",
ylab="Error anterior ", main= "Error actual vs Error anterior")
abline(h=0,col="black")
}
raizCuadrada(7, 0.00000001, 100)
El resultado es: 2.645751311 con error de 1e-08