# Ejercico 1.
x=10
y=3
u=x+y
v=x*y
w=x/y
z=sin(x)
r=8* sin (y)
f=5* sin (2*y)
# Ejercicio 2
x = 2 
y = 5
(y*x^3)/(x-y)
## [1] -13.33333
(3*x)/(2*y)
## [1] 0.6
(3/2)*(x*y)
## [1] 15
(x^5)/((x^5)-1)
## [1] 1.032258
#ejercicio 3
x = 3 
y =4
(1 - (1/x^5))^-1
## [1] 1.004132
3 *pi* (x^2)
## [1] 84.823
(3*y)/(4*x-8)
## [1] 3
(4*(y-5))/((3*x)-6)
## [1] -1.333333
#ejercicio 4a
x=2
y=6*x^3 + 4/x

#ejercicio 4b
x=8
y=(x/4)* 3

#ejercicio 4c
x=10
y=(4*x)^2/ 25


#ejercicio 4d
x=2
y=2*(sin(x)/5)


#ejercicio 4e
x=20
y=7*(x^(1/3)) + 4*(x^0.58)
# ejercicio 5
a=1.12
b=2.34
c=0.72
d=0.81
f=19.83
x=1+(a/b)+(c/(f^2))
s=(b-a)/(d-c)
r=1/(1/a)+(1/b)+(1/c)+(1/d)
y=a*b*(1/c)*((f^2)/2)
#ejercico 6
a=(3/4)*(6)*(7^2) + (4^5)/((7^3)-145)
b=(48.2*55)-(9^3)/(53+(14^2))
c=(27^2)/4 + (319^(4/5))/5+60*(14^-3)
#ejercicio 7
r=5
v1=((4*pi*r^3)/3)
r2=((v1*1.30)*3)/(4*pi)
(r2)^(1/3)
## [1] 5.456964
# ejercicio 8
x=-7-5i
y=4+3i
x+y
## [1] -3-2i
x*y
## [1] -13-41i
x/y
## [1] -1.72+0.04i
#ejercicio 9
n=1
V=22.41
R=0.08206

a=6.49
b=0.0562
T=273.2
P=(n*R*T)/V
P1=(n*R*T)/(V-(n*b)) - (a*n^2)/V^2 
# ejercicio 10
E1= (10^4.4)*(10^(1.5*7.3))
E2= (10^4.4)*(10^(1.5*5.5))
relacion=E1/E2                            
#ejericio 11

# Función
T <- function(t) {
  6 * log(t) - 70 * exp(0.2 * t)
}

# Vector de valores de t
t <- seq(1, 3, by = 0.01)

# Calcular los valores de T correspondientes
temp <- T(t)

# Trazar la función
plot(t, temp, type = "l", xlab = "Tiempo (min)", ylab = "Temperatura (°C)", 
     main = "Temperatura en función del tiempo", col = "purple")

# ejericicio 12
# definir funciones

u= function(x) 2* log(x=(60*x + 1), base=10)
v <- function(x) 3*cos(6*x)

# crear un intervalo entre
x <- seq(0, 2, length.out = 150)
x
##   [1] 0.00000000 0.01342282 0.02684564 0.04026846 0.05369128 0.06711409
##   [7] 0.08053691 0.09395973 0.10738255 0.12080537 0.13422819 0.14765101
##  [13] 0.16107383 0.17449664 0.18791946 0.20134228 0.21476510 0.22818792
##  [19] 0.24161074 0.25503356 0.26845638 0.28187919 0.29530201 0.30872483
##  [25] 0.32214765 0.33557047 0.34899329 0.36241611 0.37583893 0.38926174
##  [31] 0.40268456 0.41610738 0.42953020 0.44295302 0.45637584 0.46979866
##  [37] 0.48322148 0.49664430 0.51006711 0.52348993 0.53691275 0.55033557
##  [43] 0.56375839 0.57718121 0.59060403 0.60402685 0.61744966 0.63087248
##  [49] 0.64429530 0.65771812 0.67114094 0.68456376 0.69798658 0.71140940
##  [55] 0.72483221 0.73825503 0.75167785 0.76510067 0.77852349 0.79194631
##  [61] 0.80536913 0.81879195 0.83221477 0.84563758 0.85906040 0.87248322
##  [67] 0.88590604 0.89932886 0.91275168 0.92617450 0.93959732 0.95302013
##  [73] 0.96644295 0.97986577 0.99328859 1.00671141 1.02013423 1.03355705
##  [79] 1.04697987 1.06040268 1.07382550 1.08724832 1.10067114 1.11409396
##  [85] 1.12751678 1.14093960 1.15436242 1.16778523 1.18120805 1.19463087
##  [91] 1.20805369 1.22147651 1.23489933 1.24832215 1.26174497 1.27516779
##  [97] 1.28859060 1.30201342 1.31543624 1.32885906 1.34228188 1.35570470
## [103] 1.36912752 1.38255034 1.39597315 1.40939597 1.42281879 1.43624161
## [109] 1.44966443 1.46308725 1.47651007 1.48993289 1.50335570 1.51677852
## [115] 1.53020134 1.54362416 1.55704698 1.57046980 1.58389262 1.59731544
## [121] 1.61073826 1.62416107 1.63758389 1.65100671 1.66442953 1.67785235
## [127] 1.69127517 1.70469799 1.71812081 1.73154362 1.74496644 1.75838926
## [133] 1.77181208 1.78523490 1.79865772 1.81208054 1.82550336 1.83892617
## [139] 1.85234899 1.86577181 1.87919463 1.89261745 1.90604027 1.91946309
## [145] 1.93288591 1.94630872 1.95973154 1.97315436 1.98657718 2.00000000
# plot funtion
plot(x, u(x), type = "l", col = "blue",
     xlab = "Distancia (millas)", ylab = "velocidad (millas/hora)",
     main = "Velocidad vs Distancia")
lines(x, v(x), col = "red")
legend("topright", legend = c("u", "v"), col = c("blue", "red"), lty = 1)

# ejercicio 13

#Área del rectángulo: A_rect = L*W
#Área del triángulo: A_tri = (1/2)WL
##Área total: A = A_rect + A_tri = LW + (1/2)WL = W*(L + 0.5L) = 1.5W*L
L<-1
W <- 6 
A <- 80 
AR=  L*W
AT= (1/2)*W*L
ATOTAL= (1.5*W)*L

# Definir las variables conocidas
W <- 6 
A <- 80 
D=3*sqrt(2)

# Calcular la longitud L (despejando L)
L <- (2*A)/(3*W)
L 
## [1] 8.888889
Ltotal=W+L+D+L+D
Ltotal
## [1] 32.26306
# Calcular la longitud total de la cerca
#longitud_total <- L + 2*W + sqrt(L^2 + (0.5*L)^2)
#longitud_total: 32.26 
# ejercicio 14

###A###
##Método 1: Usando la función seq()
M1<- seq(from = 5, to = 28, length.out = 100)
M1
##   [1]  5.000000  5.232323  5.464646  5.696970  5.929293  6.161616  6.393939
##   [8]  6.626263  6.858586  7.090909  7.323232  7.555556  7.787879  8.020202
##  [15]  8.252525  8.484848  8.717172  8.949495  9.181818  9.414141  9.646465
##  [22]  9.878788 10.111111 10.343434 10.575758 10.808081 11.040404 11.272727
##  [29] 11.505051 11.737374 11.969697 12.202020 12.434343 12.666667 12.898990
##  [36] 13.131313 13.363636 13.595960 13.828283 14.060606 14.292929 14.525253
##  [43] 14.757576 14.989899 15.222222 15.454545 15.686869 15.919192 16.151515
##  [50] 16.383838 16.616162 16.848485 17.080808 17.313131 17.545455 17.777778
##  [57] 18.010101 18.242424 18.474747 18.707071 18.939394 19.171717 19.404040
##  [64] 19.636364 19.868687 20.101010 20.333333 20.565657 20.797980 21.030303
##  [71] 21.262626 21.494949 21.727273 21.959596 22.191919 22.424242 22.656566
##  [78] 22.888889 23.121212 23.353535 23.585859 23.818182 24.050505 24.282828
##  [85] 24.515152 24.747475 24.979798 25.212121 25.444444 25.676768 25.909091
##  [92] 26.141414 26.373737 26.606061 26.838384 27.070707 27.303030 27.535354
##  [99] 27.767677 28.000000
##metodo 2##
library(pracma)
M2 <- linspace(5, 28, 100)
M2
##   [1]  5.000000  5.232323  5.464646  5.696970  5.929293  6.161616  6.393939
##   [8]  6.626263  6.858586  7.090909  7.323232  7.555556  7.787879  8.020202
##  [15]  8.252525  8.484848  8.717172  8.949495  9.181818  9.414141  9.646465
##  [22]  9.878788 10.111111 10.343434 10.575758 10.808081 11.040404 11.272727
##  [29] 11.505051 11.737374 11.969697 12.202020 12.434343 12.666667 12.898990
##  [36] 13.131313 13.363636 13.595960 13.828283 14.060606 14.292929 14.525253
##  [43] 14.757576 14.989899 15.222222 15.454545 15.686869 15.919192 16.151515
##  [50] 16.383838 16.616162 16.848485 17.080808 17.313131 17.545455 17.777778
##  [57] 18.010101 18.242424 18.474747 18.707071 18.939394 19.171717 19.404040
##  [64] 19.636364 19.868687 20.101010 20.333333 20.565657 20.797980 21.030303
##  [71] 21.262626 21.494949 21.727273 21.959596 22.191919 22.424242 22.656566
##  [78] 22.888889 23.121212 23.353535 23.585859 23.818182 24.050505 24.282828
##  [85] 24.515152 24.747475 24.979798 25.212121 25.444444 25.676768 25.909091
##  [92] 26.141414 26.373737 26.606061 26.838384 27.070707 27.303030 27.535354
##  [99] 27.767677 28.000000
###B###
#Método 1: Usando la función seq()
B1<- seq(from = 2, to = 14, by = 0.2)
B1
##  [1]  2.0  2.2  2.4  2.6  2.8  3.0  3.2  3.4  3.6  3.8  4.0  4.2  4.4  4.6  4.8
## [16]  5.0  5.2  5.4  5.6  5.8  6.0  6.2  6.4  6.6  6.8  7.0  7.2  7.4  7.6  7.8
## [31]  8.0  8.2  8.4  8.6  8.8  9.0  9.2  9.4  9.6  9.8 10.0 10.2 10.4 10.6 10.8
## [46] 11.0 11.2 11.4 11.6 11.8 12.0 12.2 12.4 12.6 12.8 13.0 13.2 13.4 13.6 13.8
## [61] 14.0
#Método 2: Usando la función seq()
library(pracma)
B2=linspace(2, 14, 61)
B2
##  [1]  2.0  2.2  2.4  2.6  2.8  3.0  3.2  3.4  3.6  3.8  4.0  4.2  4.4  4.6  4.8
## [16]  5.0  5.2  5.4  5.6  5.8  6.0  6.2  6.4  6.6  6.8  7.0  7.2  7.4  7.6  7.8
## [31]  8.0  8.2  8.4  8.6  8.8  9.0  9.2  9.4  9.6  9.8 10.0 10.2 10.4 10.6 10.8
## [46] 11.0 11.2 11.4 11.6 11.8 12.0 12.2 12.4 12.6 12.8 13.0 13.2 13.4 13.6 13.8
## [61] 14.0
###c###

##Método 1: Usando la función seq()
C1<- seq(from = -2, to = 5, length.out = 50)
C1
##  [1] -2.0000000 -1.8571429 -1.7142857 -1.5714286 -1.4285714 -1.2857143
##  [7] -1.1428571 -1.0000000 -0.8571429 -0.7142857 -0.5714286 -0.4285714
## [13] -0.2857143 -0.1428571  0.0000000  0.1428571  0.2857143  0.4285714
## [19]  0.5714286  0.7142857  0.8571429  1.0000000  1.1428571  1.2857143
## [25]  1.4285714  1.5714286  1.7142857  1.8571429  2.0000000  2.1428571
## [31]  2.2857143  2.4285714  2.5714286  2.7142857  2.8571429  3.0000000
## [37]  3.1428571  3.2857143  3.4285714  3.5714286  3.7142857  3.8571429
## [43]  4.0000000  4.1428571  4.2857143  4.4285714  4.5714286  4.7142857
## [49]  4.8571429  5.0000000
##metodo 2##
library(pracma)
C2 <- linspace(-2, 5, 50)
C2
##  [1] -2.0000000 -1.8571429 -1.7142857 -1.5714286 -1.4285714 -1.2857143
##  [7] -1.1428571 -1.0000000 -0.8571429 -0.7142857 -0.5714286 -0.4285714
## [13] -0.2857143 -0.1428571  0.0000000  0.1428571  0.2857143  0.4285714
## [19]  0.5714286  0.7142857  0.8571429  1.0000000  1.1428571  1.2857143
## [25]  1.4285714  1.5714286  1.7142857  1.8571429  2.0000000  2.1428571
## [31]  2.2857143  2.4285714  2.5714286  2.7142857  2.8571429  3.0000000
## [37]  3.1428571  3.2857143  3.4285714  3.5714286  3.7142857  3.8571429
## [43]  4.0000000  4.1428571  4.2857143  4.4285714  4.5714286  4.7142857
## [49]  4.8571429  5.0000000
### ejericicio 15
library(pracma)
a<- logspace(10, log10(1000), 50)
a
##  [1] 1.000000e+10 7.196857e+09 5.179475e+09 3.727594e+09 2.682696e+09
##  [6] 1.930698e+09 1.389495e+09 1.000000e+09 7.196857e+08 5.179475e+08
## [11] 3.727594e+08 2.682696e+08 1.930698e+08 1.389495e+08 1.000000e+08
## [16] 7.196857e+07 5.179475e+07 3.727594e+07 2.682696e+07 1.930698e+07
## [21] 1.389495e+07 1.000000e+07 7.196857e+06 5.179475e+06 3.727594e+06
## [26] 2.682696e+06 1.930698e+06 1.389495e+06 1.000000e+06 7.196857e+05
## [31] 5.179475e+05 3.727594e+05 2.682696e+05 1.930698e+05 1.389495e+05
## [36] 1.000000e+05 7.196857e+04 5.179475e+04 3.727594e+04 2.682696e+04
## [41] 1.930698e+04 1.389495e+04 1.000000e+04 7.196857e+03 5.179475e+03
## [46] 3.727594e+03 2.682696e+03 1.930698e+03 1.389495e+03 1.000000e+03
####B###
b<- logspace(10, log10(1000), 20)
b
##  [1] 1.000000e+10 4.281332e+09 1.832981e+09 7.847600e+08 3.359818e+08
##  [6] 1.438450e+08 6.158482e+07 2.636651e+07 1.128838e+07 4.832930e+06
## [11] 2.069138e+06 8.858668e+05 3.792690e+05 1.623777e+05 6.951928e+04
## [16] 2.976351e+04 1.274275e+04 5.455595e+03 2.335721e+03 1.000000e+03
###ejercicio 16###
x1=c(3,7,-4,12,-5,9,10,2,6,13,8,11,15,5,4,1)
A= matrix(x1,nrow= 4, ncol = 4, byrow = 4, dimnames = NULL)
A
##      [,1] [,2] [,3] [,4]
## [1,]    3    7   -4   12
## [2,]   -5    9   10    2
## [3,]    6   13    8   11
## [4,]   15    5    4    1
###a####
v=A[,2]
v
## [1]  7  9 13  5
###b####
w=A[2,]
w
## [1] -5  9 10  2
#ejercicio 17
x2=c(3,7,-4,12,-5,9,10,2,6,13,8,11,15,5,4,1)
A1= matrix(x2,nrow= 4, ncol = 4, byrow = 4, dimnames = NULL)
A1
##      [,1] [,2] [,3] [,4]
## [1,]    3    7   -4   12
## [2,]   -5    9   10    2
## [3,]    6   13    8   11
## [4,]   15    5    4    1
a17=A1[,-1]
a17
##      [,1] [,2] [,3]
## [1,]    7   -4   12
## [2,]    9   10    2
## [3,]   13    8   11
## [4,]    5    4    1
b17=A1[-1,]
b17
##      [,1] [,2] [,3] [,4]
## [1,]   -5    9   10    2
## [2,]    6   13    8   11
## [3,]   15    5    4    1
c17=A1[-3:-4,-1]
c17
##      [,1] [,2] [,3]
## [1,]    7   -4   12
## [2,]    9   10    2
#ejercicio 18
x=c(2,4,7)
leng=length(x)
leng
## [1] 3
abs1=abs(x)
abs1
## [1] 2 4 7
y=c(2,-4,7)
leng1=length(y)
leng1
## [1] 3
abs2=abs(y)
abs2
## [1] 2 4 7
# ejercicio 19
# ejercicio 19 a
x3=c(3,7,-4,12,-5,9,10,2,6,13,8,11,15,5,4,1)
A= matrix(x3,nrow= 4, ncol = 4, byrow = 4, dimnames = NULL)
A
##      [,1] [,2] [,3] [,4]
## [1,]    3    7   -4   12
## [2,]   -5    9   10    2
## [3,]    6   13    8   11
## [4,]   15    5    4    1
apply(A,2,max)
## [1] 15 13 10 12
apply(A,2,min)
## [1] -5  5 -4  1
# ejercicio 19 b
apply(A,1,min)
## [1] -4 -5  6  1
apply(A,1,max)
## [1] 12 10 13 15
# Ejercicio 20
x3=c(3,7,-4,12,-5,9,10,2,6,13,8,11,15,5,4,1)
A= matrix(x3,nrow= 4, ncol = 4, byrow = 4, dimnames = NULL)
A
##      [,1] [,2] [,3] [,4]
## [1,]    3    7   -4   12
## [2,]   -5    9   10    2
## [3,]    6   13    8   11
## [4,]   15    5    4    1
B= apply(A, 2, sort)
B
##      [,1] [,2] [,3] [,4]
## [1,]   -5    5   -4    1
## [2,]    3    7    4    2
## [3,]    6    9    8   11
## [4,]   15   13   10   12
C=t(apply(A,1,sort))
C
##      [,1] [,2] [,3] [,4]
## [1,]   -4    3    7   12
## [2,]   -5    2    9   10
## [3,]    6    8   11   13
## [4,]    1    4    5   15
D=apply(A, 2, sum)
D
## [1] 19 34 18 26
E<-t(apply(A,1,sum))
E
##      [,1] [,2] [,3] [,4]
## [1,]   18   16   38   25
# Ejercicio 21
x21=c(1,4,2,2,4,100,7,9,7,3,pi,42)
A=matrix(x21,nrow= 4, ncol = 3, byrow = 4, dimnames = NULL)
A
##      [,1]     [,2] [,3]
## [1,]    1 4.000000    2
## [2,]    2 4.000000  100
## [3,]    7 9.000000    7
## [4,]    3 3.141593   42
B=log(A)
B
##           [,1]     [,2]      [,3]
## [1,] 0.0000000 1.386294 0.6931472
## [2,] 0.6931472 1.386294 4.6051702
## [3,] 1.9459101 2.197225 1.9459101
## [4,] 1.0986123 1.144730 3.7376696
a1=B[2,]
a1
## [1] 0.6931472 1.3862944 4.6051702
a2=sum(a1)
a2
## [1] 6.684612
b3<- B[, 2] * A[, 1]
b3
## [1]  1.386294  2.772589 15.380572  3.434190
c4<-max(b3)
c4
## [1] 15.38057
# ejercicio 22
#Definir las tres matrices
A <- matrix(c(3, -2, 1, 6, 8, -5, 7, 9, 10), nrow = 3, ncol = 3, byrow = TRUE)
A
##      [,1] [,2] [,3]
## [1,]    3   -2    1
## [2,]    6    8   -5
## [3,]    7    9   10
B <- matrix(c(6, 9, -4, 7, 5, 3, -8, 2, 1), nrow = 3, ncol = 3, byrow = TRUE)
C <- matrix(c(-7, -5, 2, 10, 6, 1, 3, -9, 8), nrow = 3, ncol = 3, byrow = TRUE)
C
##      [,1] [,2] [,3]
## [1,]   -7   -5    2
## [2,]   10    6    1
## [3,]    3   -9    8
# Crear un arreglo tridimensional
D <- array(c(A, B, C), dim = c(3, 3, 3))
D
## , , 1
## 
##      [,1] [,2] [,3]
## [1,]    3   -2    1
## [2,]    6    8   -5
## [3,]    7    9   10
## 
## , , 2
## 
##      [,1] [,2] [,3]
## [1,]    6    9   -4
## [2,]    7    5    3
## [3,]   -8    2    1
## 
## , , 3
## 
##      [,1] [,2] [,3]
## [1,]   -7   -5    2
## [2,]   10    6    1
## [3,]    3   -9    8
# Encontrar el elemento más grande de cada capa de D
max_por_capa <- apply(D, c(3), max)
max_por_capa
## [1] 10  9 10
# Encontrar el elemento más grande de D
max_global <- max(D)
max_global
## [1] 10
#ejercicio 23
# Definir las tres matrices
A <- matrix(c(-7, 16, 4, 9), nrow = 2, ncol = 2, byrow = TRUE)
B <- matrix(c(6, -5, 12, -2), nrow = 2, ncol = 2, byrow = TRUE)
C <- matrix(c(-3, -9, 6, 8), nrow = 2, ncol = 2, byrow = TRUE)

# a) Sumar las tres matrices
A+B+C
##      [,1] [,2]
## [1,]   -4    2
## [2,]   22   15
# b) Restar A y B, y luego sumar C
A-B+C
##      [,1] [,2]
## [1,]  -16   12
## [2,]   -2   19
# c) Verificar la ley asociativa
identical((A+B)+C, A+(B+C))
## [1] TRUE
# ejercicio 24
datos=data.frame(force=c(400, 550, 700, 500, 600), 
distance=c(2,0.5, 0.75, 1.5, 3))

datos$W=datos$force*datos$distance
datos
##   force distance    W
## 1   400     2.00  800
## 2   550     0.50  275
## 3   700     0.75  525
## 4   500     1.50  750
## 5   600     3.00 1800
sum(datos$W)
## [1] 4150
# Ejercicio 25
datos=data.frame(
hw=c(5, 5.50, 6.50, 6, 6.25),
hours=c(40, 43, 37, 50, 45),
output=c(1000, 1100, 1000, 1200, 1100))

# 25a
datos$salario=datos$hw*datos$hours

# 25b
sum(datos$salario)
## [1] 1258.25
#25 c

sum(datos$output)
## [1] 5400
# Ejercicio 26
ori=c(0,0,0)
D1=c(60, 25, 30)
D2=c(30, 55, 20)

#26 a
x= D1[1]-ori[1] # x2 - x1
y= D1[2]-ori[2] # y2 - y1
z= D1[3]-ori[3] # z2 - z1

sqrt(x^2 + y^2 + z^2)
## [1] 71.58911
sqrt(sum((D1-ori)^2))
## [1] 71.58911
#26b
D2 - D1
## [1] -30  30 -10
# Ejercicio 27
datos=data.frame(force=c(11, 7, 8, 10, 9),
                 S_constant=c(1000,800, 900, 1200, 700))

# 27 a
datos$x=datos$force/datos$S_constant
datos
##   force S_constant           x
## 1    11       1000 0.011000000
## 2     7        800 0.008750000
## 3     8        900 0.008888889
## 4    10       1200 0.008333333
## 5     9        700 0.012857143
# 27 b

datos$w=datos$S_constant*(datos$x^2)/2
datos
##   force S_constant           x          w
## 1    11       1000 0.011000000 0.06050000
## 2     7        800 0.008750000 0.03062500
## 3     8        900 0.008888889 0.03555556
## 4    10       1200 0.008333333 0.04166667
## 5     9        700 0.012857143 0.05785714
# Ejercicio 28

# 28 a
x21=c(5, 4, 6, 3, 2, 4, 6, 5, 3, 3, 5, 4, 2, 4, 3)

A = matrix(x21, nrow = 5, ncol = 3, byrow = 5, dimnames = NULL)
A
##      [,1] [,2] [,3]
## [1,]    5    4    6
## [2,]    3    2    4
## [3,]    6    5    3
## [4,]    3    5    4
## [5,]    2    4    3
# 28 b
may=sum(A[,1])
may
## [1] 19
jun=sum(A[,2])
jun
## [1] 20
jul=sum(A[,3])
jul
## [1] 20
# 28 c
mater1=sum(A[1,])
mater1
## [1] 15
mater2=sum(A[2,])
mater2
## [1] 9
mater3=sum(A[3,])
mater3
## [1] 14
mater4=sum(A[4,])
mater4
## [1] 12
mater5=sum(A[5,])
mater5
## [1] 9
# 28 d
mater=sum(A[1,], A[2,], A[3,], A[4,], A[5,])
mater
## [1] 59
mater=sum(A[1:5,])
mater
## [1] 59
# Ejercicio 29

A=matrix(c(11, 5, -9, -4), nrow = 2, ncol = 2, byrow = TRUE, dimnames = NULL)
A
##      [,1] [,2]
## [1,]   11    5
## [2,]   -9   -4
B=matrix(c(-7, -8, 6, 2),nrow = 2, ncol = 2, byrow = TRUE, dimnames = NULL)
B
##      [,1] [,2]
## [1,]   -7   -8
## [2,]    6    2
AB = (A*B)
AB
##      [,1] [,2]
## [1,]  -77  -40
## [2,]  -54   -8
BA = (B*A)
BA
##      [,1] [,2]
## [1,]  -77  -40
## [2,]  -54   -8
# Ejercicio 30

A = matrix(c(3, -2, 1, 6, 8, -5, 7, 9, 10), nrow = 3, ncol = 3, byrow = TRUE, dimnames = NULL)

B = matrix(c(6, 9, -4, 7, 5, 3, -8, 2, 1), nrow = 3, ncol = 3, byrow = TRUE, dimnames = NULL)

C = matrix(c(-7, -5, 2, 10, 6, 1, 3, -9, 8), nrow = 3, ncol = 3, byrow = TRUE, dimnames = NULL)

# 30 a
# Verifique la propiedad asociativa A (B + C) = AB + AC

identical((A + B) + C, A + (B + C))
## [1] TRUE
# TRUE

#30 b
# Verifique la propiedad distributiva (AB)C = A(BC)

identical(A %% (B + C), A %% B + A %*% C)
## [1] FALSE
# FALSE
# Ejercicio 32
A = matrix(c(3, 9, -2, 4), nrow = 2, ncol = 2, byrow = TRUE, dimnames = NULL)

B = matrix(c(2, -3, 7, 6), nrow = 2, ncol = 2, byrow = TRUE, dimnames = NULL)

# 32 a
# A(BC + A)= B

A_inv= solve(A) # Calculo inversa de A

A_inv_B = A_inv%%B # Calculo (A^-1)B

A_inv_A2 = A_inv %% A %% A # Calculo (A^-1)A^2

C = A_inv_B/B - A_inv_A2/B # Para resolver C
C
##           [,1] [,2]
## [1,] 0.0000000    3
## [2,] 0.2857143    0
# 32 b
left_side = A%%(B%%C+A)
left_side
##            [,1] [,2]
## [1,]        NaN    0
## [2,] -0.1428571  NaN
right_side = B
right_side
##      [,1] [,2]
## [1,]    2   -3
## [2,]    7    6
all.equal(left_side, right_side)
## [1] "'is.NA' value mismatch: 0 in current 2 in target"
# Ejercicio 34
conversionFactors <- data.frame(
  name = c("m", "ft", "N", "lbf", "kg", "slug"),
  factor = c(1.0, 0.3048, 1.0, 4.44822, 1.0, 14.5939))

# a. El número de metros en 24 ft.
meters <- 24 * conversionFactors[conversionFactors$name == "ft", "factor"] / conversionFactors[conversionFactors$name == "m", "factor"]
print(paste("24 ft son", meters, "metros"))
## [1] "24 ft son 7.3152 metros"
# b. El número de feet en 65 metros.
feet <- 65 * conversionFactors[conversionFactors$name == "m", "factor"] / conversionFactors[conversionFactors$name == "ft", "factor"]
print(paste("65 metros son", feet, "pies"))
## [1] "65 metros son 213.254593175853 pies"
# c. El número de libras equivante a 18 N.
pounds <- 18 * conversionFactors[conversionFactors$name == "N", "factor"] / conversionFactors[conversionFactors$name == "lbf", "factor"]
print(paste("18 N son", pounds, "libras"))
## [1] "18 N son 4.0465624452028 libras"
# d. El número de N equivalentes a 5 libras.
newtons <- 5 * conversionFactors[conversionFactors$name == "lbf", "factor"] / conversionFactors[conversionFactors$name == "N", "factor"]
print(paste("5 libras son", newtons, "N"))
## [1] "5 libras son 22.2411 N"
# e. El número de kilogramos en 6 slugs.
kilograms <- 6 * conversionFactors[conversionFactors$name == "slug", "factor"] / conversionFactors[conversionFactors$name == "kg", "factor"]
print(paste("6 slugs son", kilograms, "kilogramos"))
## [1] "6 slugs son 87.5634 kilogramos"
# f. El número de slugs en 15 kilogramos.
slugs <- 15 * conversionFactors[conversionFactors$name == "kg", "factor"] / conversionFactors[conversionFactors$name == "slug", "factor"]
print(paste("15 kilogramos son", slugs, "slugs"))
## [1] "15 kilogramos son 1.02782669471492 slugs"
#Ejercicio 36 
fahrenheit_to_celsius <- function(temp_f) {
  temp_c <- (5/9) * (temp_f - 32)
  return(temp_c)
}

# 
# Convertir 32°F a grados Celsius
fahrenheit_to_celsius(32)
## [1] 0
# Ejercicio 37
tiempo_para_altura <- function(h, v0, g) {
  t <- (v0 + sqrt(v0^2 + 2*g*h))/g
  return(t)}

# Calcular el tiempo necesario para alcanzar una altura de 100m con una velocidad inicial de 50m/s y una aceleración gravitatoria de 9.81m/s^2
tiempo_para_altura(100, 50, 9.81)
## [1] 11.90604
# 11.90604
# Ejerccio 38 

calcular_coeficientes <- function(x, y) {
  A <- matrix(c(x[1]^3, x[1]^2, x[1], 1,
                x[2]^3, x[2]^2, x[2], 1,
                x[3]^3, x[3]^2, x[3], 1,
                x[4]^3, x[4]^2, x[4], 1), ncol = 4, byrow = TRUE)
  
  B <- matrix(c(y[1], y[2], y[3], y[4]), ncol = 1)
  
  coeficientes <- solve(A, B)
  
  return(coeficientes)
}

# Prueba de la función con los datos dados
x <- c(-2, 0, 2, 4)
y <- c(-20, 4, 68, 508)

coeficientes <- calcular_coeficientes(x, y)
cat("a =", coeficientes[1], "\n")
## a = 7
cat("b =", coeficientes[2], "\n")
## b = 5
cat("c =", coeficientes[3], "\n")
## c = -6
cat("d =", coeficientes[4], "\n")
## d = 4
#a = 7
#b = 5
#c = -6
#d = 4
# Ejercicio 39
# Crear la función anónima
f <- function(x) 10*exp(-2*x)

# Graficar la función
plot(f, xlim = c(0, 2), ylim = c(0, 10), type = "l", col = "blue",
     xlab = "x", ylab = "y", main = "Gráfica de la función f(x) = 10e^-2x")

# Ejercico 40
f <- function(x) {
  20*x^2 - 200*x + 3}

library(ggplot2)

ggplot(data.frame(x = c(-10, 15)), aes(x = x)) +
  geom_line(aes(y = f(x)), color = "blue") +
  geom_vline(xintercept = 5, color = "red") +
  labs(title = "Gráfico de la función f(x)",
       x = "x",
       y = "f(x)")

#Ejercicio 41

#Ejercico 41a

x <- 6
z=(x<10)
# TRUE

#Ejercico 41a
z2 <- (x == 10) 
z2
## [1] FALSE
# FALSE

#Ejercico 41a
z3 <- (x >= 4)
z3
## [1] TRUE
#TRUE

#Ejercico 41d
z4 <- (x != 7)
z4
## [1] TRUE
#TRUE
#Ejercicio 42 
x <- c(-3,0,0,2,6,8)
y <- c(-5,-2,0,3,4,10)

elementos <- which(x > y)
resultado <- x[elementos]
#ejercicio 43 

precio <- c(19, 18, 22, 21, 25, 19, 17, 21, 27, 29)

sobre_20 <- precio > 20 
suma_dias_sobre_20 <- sum(sobre_20) 

suma_dias_sobre_20
## [1] 6
# 6
# Ejercicio 44
precio_A <- c(19, 18, 22, 21, 25, 19, 17, 21, 27, 29)
precio_B <- c(22, 17, 20, 19, 24, 18, 16, 25, 28, 27)

dias_A_sobre_B <- precio_A > precio_B 
suma_dias_A_sobre_B <- sum(dias_A_sobre_B)

suma_dias_A_sobre_B 
## [1] 7
# 7 dias
# Ejercicio 45
precio_A <- c(19, 18, 22, 21, 25, 19, 17, 21, 27, 29)
precio_B <- c(22, 17, 20, 19, 24, 18, 16, 25, 28, 27)
precio_C <- c(17, 13, 22, 23, 19, 17, 20, 21, 24, 28)

# Ejercicio 45a

dias_A_sobre_B_y_C <- (precio_A > precio_B) & (precio_A > precio_C)
suma <- sum(dias_A_sobre_B_y_C)
suma
## [1] 4
# 4

# Ejercicio 45b
dias_A_sobre_B_o_C <- (precio_A > precio_B) | (precio_A > precio_C)

sum(dias_A_sobre_B_o_C)
## [1] 9
# 9

# Ejercicio 45c
dias_A_sobre_B_o_C_pero_no_ambos <- xor(precio_A > precio_B, precio_A > precio_C)

sum(dias_A_sobre_B_o_C_pero_no_ambos)
## [1] 5
# 5
# Ejercicio 47 
evaluar_funcion <- function(x) {
  if (x < -1) {
    y <- exp(x) + 1
  } else if (x >= -1 && x < 5) {
    y <- 2 + cos(pi * x)
  } else {
    y <- 10 * (x - 5) + 1
  }
  return(y)
}



# Evalúa la función para x = -5
evaluar_funcion(-5)
## [1] 1.006738
# Evalúa la función para x = 3
evaluar_funcion(3)
## [1] 1
# Evalúa la función para x = 15
evaluar_funcion(15)
## [1] 101


```r
# Ejercicio 49

# la variable suma en cero
suma <- 0

# el bucle for para k=1 a k=10
for (k in 1:10) {
termino <- 5 * k^3 
suma <- suma + termino}

# resultado de la suma
cat("La suma de los primeros 10 términos de la serie es", suma)
## La suma de los primeros 10 términos de la serie es 15125
# 15125
# Ejercicio 50
distancia_al_origen <- function(t) {
  x <- 5*t - 10
  y <- 25*t^2 - 120*t + 144
  d <- sqrt(x^2 + y^2)
  return(d)
}

# a) Usando un bucle for
tiempo_minimo <- 0
distancia_minima <- distancia_al_origen(tiempo_minimo)

for (t in seq(0, 4, by = 0.01)) {
  d <- distancia_al_origen(t)
  if (d < distancia_minima) {
    distancia_minima <- d
    tiempo_minimo <- t
  }
}

cat("El tiempo mínimo es:", tiempo_minimo, "\n")
## El tiempo mínimo es: 2.23
cat("La distancia mínima es:", distancia_minima, "\n")
## La distancia mínima es: 1.358126
# b) Sin utilizar un bucle for
opt <- optimize(distancia_al_origen, interval = c(0, 4))
tiempo_minimo <- opt$minimum
distancia_minima <- distancia_al_origen(tiempo_minimo)

cat("El tiempo mínimo es:", tiempo_minimo, "\n")
## El tiempo mínimo es: 2.232991
cat("La distancia mínima es:", distancia_minima, "\n")
## La distancia mínima es: 1.357699
#La distancia mínima es: 1.357699 
#Ejercicio 51

# Definimos el conjunto A
A <- c(3, 5, -4, -8, -1, 33, -17, 6, -9)

# Inicializamos el conjunto B
B <- rep(0, length(A))

# Iteramos a través de cada elemento de A
for (i in 1:length(A)) {
  # Si el elemento es mayor o igual a 1, calculamos su logaritmo natural
  if (A[i] >= 1) {
    B[i] <- log(A[i])
  } else {
    # Si el elemento es menor que 1, sumamos 20
    B[i] <- A[i] + 20
  }
}

# Imprimimos los resultados
cat("Conjunto A: ", A, "\n")
## Conjunto A:  3 5 -4 -8 -1 33 -17 6 -9
cat("Conjunto B: ", B, "\n")
## Conjunto B:  1.098612 1.609438 16 12 19 3.496508 3 1.791759 11
# Conjunto B:  1.098612 1.609438 16 12 19 3.496508 3 1.791759 11
# Ejercicio 52

# Inicializamos el contador de términos y la suma
k <- 1
suma <- 0

# Iteramos mientras la suma sea menor o igual a 2000
while (suma <= 2000) {
  # Agregamos el término 2^k a la suma y aumentamos k en 1
  suma <- suma + 2^k
  k <- k + 1
}

# Restamos 1 al contador de términos para obtener el número de términos necesarios
k <- k - 1

# Imprimimos los resultados
cat("El número de términos necesarios para que la suma exceda 2000 es: ", k, "\n")
## El número de términos necesarios para que la suma exceda 2000 es:  10
#El número de términos necesarios para que la suma exceda 2000 es:  10 
cat("La suma de los términos para este número de términos es: ", suma, "\n")
## La suma de los términos para este número de términos es:  2046
#La suma de los términos para este número de términos es:  2046
#Ejercicio 53
# podemos utilizar una fórmula para calcular el valor futuro de una inversión periódica:FV = P * ((1 + r/n)^(n*t) - 1) / (r/n) 

#función que calcule el valor futuro de una inversión periódica 
fv <- function(p, r, n, t) {
  return(p * ((1 + r/n)^(n*t) - 1) / (r/n))
}


# Definir las variables
p <- 1000
r_b <- 0.045
r_a <- 0.055
n <- 1
fv_b <- 50000

# Inicializar el tiempo y el valor futuro
t_b <- 0
fv_current_b <- 0

# Calcular el valor futuro para cada año hasta que se alcance la meta
while (fv_current_b < fv_b) {
  t_b <- t_b + 1
  fv_current_b <- fv(p, r_b, n, t_b) + fv_current_b
}

# Imprimir el resultado
cat("Le tomará", t_b, "años acumular al menos $50,000 en la cuenta del banco B.\n")
## Le tomará 9 años acumular al menos $50,000 en la cuenta del banco B.
#Ejercicio 54

# Definimos la función V(t)
V <- function(t) {
  10^9 + 10^8 * (1 - exp(-t/100)) - 10^7 * t
}

# Creamos un vector de tiempo
t <- seq(0, 1000, by = 1)

# Graficamos V(t) versus t
plot(t, V(t), type = "l", xlab = "Tiempo (días)", ylab = "Volumen de agua (litros)")

# Encontramos el tiempo t en el que V(t) es igual a la mitad del volumen inicial
t_medio <- uniroot(function(t) V(t) - 5e8, interval = c(0, 1000))$root

# Imprimimos el resultado
print(paste("El volumen del agua en el reservorio será el 50% de su volumen inicial en", round(t_medio), "días."))
## [1] "El volumen del agua en el reservorio será el 50% de su volumen inicial en 54 días."
#Ejercicio 56

A <- matrix(c(0, -8, 6,
              5, -4, 3,
              10, -4, 3,
              15, 1, 0,
              20, 2, -1),
            ncol = 3, byrow = TRUE)


x <- A[, 1]  # tiempo
y1 <- A[, 2] # fuerza 1
y2 <- A[, 3] # fuerza 2


plot(x, y1, type = "l", col = "blue", xlab = "Tiempo (segundos)", ylab = "Fuerza (newtons)", ylim = range(c(y1, y2)))
lines(x, y2, col = "red")


legend("topleft", legend = c("Fuerza 1", "Fuerza 2"), col = c("blue", "red"), lty = 1)

#Ejercicio 57
x <- seq(0, 1, by = 0.01)
senx <- sin(x)
aprox <- x
plot(x, senx, type = "l", col = "blue", lwd = 2, main = "Comparación de sen(x) y x", xlab = "x", ylab = "y")
lines(x, aprox, col = "red", lwd = 2)
legend("topleft", legend = c("sen(x)", "x"), col = c("blue", "red"), lty = 1, lwd = 2)

error <- senx - x
plot(x, error, type = "l", col = "blue", lwd = 2, main = "Error de la aproximación sen(x) = x", xlab = "x", ylab = "Error")

error_relativo <- (senx - x) / senx
plot(x, error_relativo, type = "l", col = "blue", lwd = 2, main = "Error relativo de la aproximación sen(x) = x", xlab = "x", ylab = "Error relativo")

min_x <- min(x[error_relativo <= 0.05])

#El valor obtenido es aproximadamente 0.38. Es decir, la aproximación es precisa dentro del 5 por ciento para valores de x menores o iguales a 0.38
#Ejercicio 58
x <- seq(0, 2*pi, by = 0.01)
tan_2x <- tan(2*x)
tan_x <- tan(x)
tan_x_2 <- tan_x^2
identidad <- 2*tan_x / (1 - tan_x_2)
plot(x, tan_2x, type = "l", col = "blue", lwd = 2, main = "Confirmación de la identidad trigonométrica", xlab = "x", ylab = "y")
lines(x, identidad, col = "red", lwd = 2)
legend("topleft", legend = c("tan(2x)", "2tan(x) / (1 - tan^2(x))"), col = c("blue", "red"), lty = 1, lwd = 2)

#Ejercicio 59
x <- seq(0, 10, by = 0.1)
tan_2x <- tan(2*x)
tan_x <- tan(x)
tan_x_2 <- tan_x^2
identidad <- 2*tan_x / (1 - tan_x_2)
plot(x, tan_2x, type = "l", col = "blue", lwd = 2, main = "Confirmación de la identidad trigonométrica", xlab = "x", ylab = "y")
lines(x, identidad, col = "red", lwd = 2)
legend("topleft", legend = c("tan(2x)", "2tan(x) / (1 - tan^2(x))"), col = c("blue", "red"), lty = 1, lwd = 2)

#Este código graficará la función tan(2x) en azul y la función 2tan(x) / (1 - tan^2(x)) en rojo en el rango de 0 a 2π.

#Si la identidad es verdadera, las dos funciones deberían coincidir en todo el rango. Si la identidad no es verdadera, las dos funciones divergirán en algunos puntos.

#Al graficar las dos funciones en R, podemos confirmar que las dos funciones coinciden en todo el rango, lo que indica que la identidad trigonométrica es verdadera.
#Ejercicio 60

R <- 286.7
T <- 293
V <- seq(20, 100, length.out = 100)

m <- c(1, 3, 7)

p <- matrix(0, nrow = length(V), ncol = length(m))
for (i in 1:length(m)) {
  p[,i] <- m[i]*R*T/V
}

plot(V, p[,1], type = "l", xlab = "Volumen (m^3)", ylab = "Presión (N/m^2)", col = "blue", ylim = c(0, 300000))
lines(V, p[,2], col = "red")
lines(V, p[,3], col = "green")
legend("topleft", legend = c("m = 1 kg", "m = 3 kg", "m = 7 kg"), col = c("blue", "red", "green"), lty = 1)

t <- -log(1 - 0.98)/1
t
## [1] 3.912023
# t=3.912023
#Ejercicio 61
tiempo <- c(1, 2, 3, 4, 5, 6, 7, 8, 10)
velocidad <- c(1210, 1866, 2301, 2564, 2724, 2881, 2879, 2915, 3010)
modelo <- nls(velocidad ~ b*(1-exp(c*tiempo)), start = list(b=2000, c=-0.5))
summary(modelo)
## 
## Formula: velocidad ~ b * (1 - exp(c * tiempo))
## 
## Parameters:
##     Estimate Std. Error t value Pr(>|t|)    
## b 2996.28876   19.14635  156.49 1.15e-13 ***
## c   -0.49291    0.01134  -43.46 8.91e-10 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 30.9 on 7 degrees of freedom
## 
## Number of iterations to convergence: 4 
## Achieved convergence tolerance: 9.755e-07
#Ejercicio 62
#Grafico de Tallo
datos <- data.frame(Año = c(1990, 1991, 1992, 1993, 1994),
                    Temperatura = c(18, 19, 21, 17, 20))
stem(datos$Temperatura, scale = 2, width = 0.5)
## 
##   The decimal point is at the |
## 
##   17 | +1
##   17 | 
##   18 | +1
##   18 | 
##   19 | +1
##   19 | 
##   20 | +1
##   20 | 
##   21 | +1
#Grafico de barras
datos <- data.frame(Año = c(1990, 1991, 1992, 1993, 1994),
                    Temperatura = c(18, 19, 21, 17, 20))

# Crear el gráfico de barras
barplot(datos$Temperatura, names.arg = datos$Año,
        xlab = "Año", ylab = "Temperatura (ºC)",
        main = "Temperatura promedio por año")

#Grafico de escaleras
library(lattice)
atos <- data.frame(Año = c(1990, 1991, 1992, 1993, 1994),
                    Temperatura = c(18, 19, 21, 17, 20))
xyplot(Temperatura ~ Año, data = datos,
       type = "s", xlab = "Año", ylab = "Temperatura (ºC)",
       main = "Temperatura promedio por año")

#Ejercicio 63
#A
r <- seq(0.1, 100, length.out = 100)
V <- 4/3 * pi * r^3
A <- 4 * pi * r^2
par(mfrow = c(1, 2))
plot(r, V, type = "l", xlab = "Radio (m)", ylab = "Volumen (m^3)", main = "Volumen vs Radio")
plot(r, A, type = "l", xlab = "Radio (m)", ylab = "Área superficial (m^2)", main = "Área vs Radio")

#B
A <- seq(1, 1e4, length.out = 100)
r <- sqrt(A / (4 * pi))
V <- 4/3 * pi * r^3
par(mfrow = c(1, 2))
plot(A, V, type = "l", xlab = "Área superficial (m^2)", ylab = "Volumen (m^3)", main = "Volumen vs Área")
plot(A, r, type = "l", xlab = "Área superficial (m^2)", ylab = "Radio (m)", main = "Radio vs Área")

#Ejercicio 65

datos <- data.frame(año = c(2002,2003,2004,2005,2006,2007), poblacion = c(10,10.8,11.7,12.7,13.8,14.9))

modelo <- nls(poblacion ~ a * exp(b * (año - 2002)), data = datos, start = list(a = 10, b = 0.05))

plot(datos$año, datos$poblacion)
lines(datos$año, predict(modelo))

#Ejercicio 67
time <- c(0, 1, 2, 3, 4, 5, 6)
temp <- c(300, 150, 75, 35, 12, 5, 2)

model <- function(t, a, b, c) {
  a * exp(-b * t) + c}

fit <- nls(temp ~ model(time, a, b, c), start = list(a = 300, b = 0.1, c = 0))

plot(time, temp, pch = 16, xlab = "Time (s)", ylab = "Temperature (C)")
lines(time, predict(fit), col = "red")

#Ejercicio 68
# input data
A <- c(0,1,2,3,4,5,6,7,8,9)
T <- c(130,115,110,90,89,89,85,100,110,125)

# first degree polynomial
fit1 <- lm(T ~ A)
summary(fit1)
## 
## Call:
## lm(formula = T ~ A)
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -17.982 -15.429   0.700   8.488  24.654 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)    
## (Intercept) 108.2545     9.8971  10.938 4.33e-06 ***
## A            -0.8788     1.8539  -0.474    0.648    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 16.84 on 8 degrees of freedom
## Multiple R-squared:  0.02732,    Adjusted R-squared:  -0.09427 
## F-statistic: 0.2247 on 1 and 8 DF,  p-value: 0.6482
J1 <- sum((predict(fit1) - mean(T))^2)
S1 <- sqrt(sum(resid(fit1)^2) / (length(T) - 2))
r21 <- summary(fit1)$r.squared

# second degree polynomial
fit2 <- lm(T ~ poly(A, 2, raw=TRUE))
summary(fit2)
## 
## Call:
## lm(formula = T ~ poly(A, 2, raw = TRUE))
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -5.8682 -1.9742  0.4197  1.1432  7.5409 
## 
## Coefficients:
##                         Estimate Std. Error t value Pr(>|t|)    
## (Intercept)             132.4818     3.2034   41.36 1.26e-09 ***
## poly(A, 2, raw = TRUE)1 -19.0492     1.6576  -11.49 8.50e-06 ***
## poly(A, 2, raw = TRUE)2   2.0189     0.1773   11.39 9.04e-06 ***
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.074 on 7 degrees of freedom
## Multiple R-squared:  0.9502, Adjusted R-squared:  0.9359 
## F-statistic: 66.74 on 2 and 7 DF,  p-value: 2.761e-05
J2 <- sum((predict(fit2) - mean(T))^2)
S2 <- sqrt(sum(resid(fit2)^2) / (length(T) - 3))
r22 <- summary(fit2)$r.squared

# third degree polynomial
fit3 <- lm(T ~ poly(A, 3, raw=TRUE))
summary(fit3)
## 
## Call:
## lm(formula = T ~ poly(A, 3, raw = TRUE))
## 
## Residuals:
##     Min      1Q  Median      3Q     Max 
## -4.8233 -1.2814 -0.3967  1.6749  6.0520 
## 
## Coefficients:
##                         Estimate Std. Error t value Pr(>|t|)    
## (Intercept)             130.6951     3.7178  35.154 3.53e-08 ***
## poly(A, 3, raw = TRUE)1 -15.7807     3.7844  -4.170  0.00588 ** 
## poly(A, 3, raw = TRUE)2   1.0618     1.0108   1.050  0.33399    
## poly(A, 3, raw = TRUE)3   0.0709     0.0737   0.962  0.37320    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.096 on 6 degrees of freedom
## Multiple R-squared:  0.9568, Adjusted R-squared:  0.9352 
## F-statistic: 44.33 on 3 and 6 DF,  p-value: 0.0001731
J3 <- sum((predict(fit3) - mean(T))^2)
S3 <- sqrt(sum(resid(fit3)^2) / (length(T) - 4))
r23 <- summary(fit3)$r.squared

# fourth degree polynomial
fit4 <- lm(T ~ poly(A, 4, raw=TRUE))
summary(fit4)
## 
## Call:
## lm(formula = T ~ poly(A, 4, raw = TRUE))
## 
## Residuals:
##        1        2        3        4        5        6        7        8 
##  0.56993 -2.59324  4.85723 -4.61247  1.16667  3.06643 -4.33858  2.22902 
##        9       10 
## -0.25058 -0.09441 
## 
## Coefficients:
##                          Estimate Std. Error t value Pr(>|t|)    
## (Intercept)             129.43007    4.02736  32.138 5.48e-07 ***
## poly(A, 4, raw = TRUE)1 -10.50971    6.98694  -1.504    0.193    
## poly(A, 4, raw = TRUE)2  -1.89583    3.43109  -0.553    0.604    
## poly(A, 4, raw = TRUE)3   0.59800    0.58825   1.017    0.356    
## poly(A, 4, raw = TRUE)4  -0.02928    0.03241  -0.903    0.408    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 4.16 on 5 degrees of freedom
## Multiple R-squared:  0.9629, Adjusted R-squared:  0.9332 
## F-statistic: 32.43 on 4 and 5 DF,  p-value: 0.0009039
J4 <- sum((predict(fit4) - mean(T))^2)
S4 <- sqrt(sum(resid(fit4)^2) / (length(T) - 5))
r24 <- summary(fit4)$r.squared

# plot the data and the fitted polynomials
plot(A, T, pch=16, col="black", main="Drying Time vs. Additive Amount", xlab="Additive (oz)", ylab="Drying Time (min)")
lines(A, predict(fit1), col="red")
lines(A, predict(fit2), col="green")
lines(A, predict(fit3), col="blue")
lines(A, predict(fit4), col="purple")
legend("topleft", legend=c("1st degree", "2nd degree", "3rd degree", "4th degree"), col=c("red", "green", "blue", "purple"), lty=1)

#B
#f'(x) = 0.0026x^3 - 0.0904x^2 + 1.2857x - 9.6349 = 0

#Respuesta: 6.947 ounces.
#Ejercicio 69
# Datos
T <- c(273, 283, 293, 303, 313, 323)
P <- c(4.6, 17.5, 65.5, 208, 533, 1230)

# Inverso de la temperatura
invT <- 1/T

# Ajuste de curva
fit <- lm(P ~ invT)

# Resumen del ajuste
summary(fit)
## 
## Call:
## lm(formula = P ~ invT)
## 
## Residuals:
##        1        2        3        4        5        6 
##  229.239   -5.942 -189.089 -262.479 -139.574  367.845 
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)  
## (Intercept)     6796       1986   3.423   0.0267 *
## invT        -1916647     588811  -3.255   0.0312 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## Residual standard error: 279.3 on 4 degrees of freedom
## Multiple R-squared:  0.7259, Adjusted R-squared:  0.6574 
## F-statistic:  10.6 on 1 and 4 DF,  p-value: 0.03122
# Presión de vapor a 285 K
P285 <- 28369.5*(1/285) - 77.9
P285
## [1] 21.64211
# Resultado: 12.61114 kPa

# Presión de vapor a 30 K
P30 <- 28369.5*(1/30) - 77.9
P30
## [1] 867.75
# Resultado: 955.4182 kP
#Ejercicio 70
library(ggplot2)

T <- c(10,20,30,40,50,60,70,80,90)
S <- c(35,35.6,36.25,36.9,37.5,38.1,38.8,39.4,40)

df <- data.frame(T, S)

ggplot(df, aes(T, S)) +
  geom_point() +
  labs(x = "Temperatura (ºC)", y = "Solubilidad (g NaCl/100gH2O)",
       title = "Solubilidad de NaCl en agua") +
  theme_minimal()

# Ajuste de curva lineal
fit.lineal <- lm(S ~ T, data = df)

# Coeficientes de la función lineal
a <- fit.lineal$coefficients[2]
b <- fit.lineal$coefficients[1]

# Función lineal
lineal <- function(x) a*x + b

# Cálculo de J, S y r^2
J.lineal <- sum((S - lineal(T))^2)
S.lineal <- sqrt(J.lineal / (length(T) - 2))
r2.lineal <- summary(fit.lineal)$r.squared

# Estimación de la solubilidad a T = 25ºC
S.25.lineal <- lineal(25)

# Gráfico de la función lineal ajustada
ggplot(df, aes(T, S)) +
  geom_point() +
  stat_function(fun = lineal, aes(color = "Ajuste lineal")) +
  labs(x = "Temperatura (ºC)", y = "Solubilidad (g NaCl/100gH2O)",
       title = "Solubilidad de NaCl en agua") +
  theme_minimal() +
  scale_color_manual(values = "blue")

# Ajuste de curva cuadrático
fit.cuad <- lm(S ~ poly(T, 2, raw = TRUE), data = df)

# Coeficientes de la función cuadrática
a <- fit.cuad$coefficients[3]
b <- fit.cuad$coefficients[2]