# Load the ggplot2 library for plotting
library(ggplot2)

# Define the Taylor series function for cosine
cos_taylor_series <- function(x, terms = 10) {
  # Initialize the sum of the series
  sum <- 0
  
  # Loop to calculate each term in the Taylor series
  for (n in 0:(terms - 1)) {
    # Compute the nth term of the series: (-1)^n / (2n)! * x^(2n)
    term <- ((-1)^n / factorial(2 * n)) * x^(2 * n)
    
    # Add the nth term to the sum
    sum <- sum + term
  }
  
  # Return the computed sum of the series
  return(sum)
}

# Create a sequence of x values from -2Ï€ to 2Ï€
x_values <- seq(-2*pi, 2*pi, length.out = 100)

# Calculate cos(x) and cos(-x) for each x using the Taylor series
data <- data.frame(
  x = x_values,
  cos_x = sapply(x_values, cos_taylor_series),      # Apply the Taylor series function for cos(x)
  cos_neg_x = sapply(-x_values, cos_taylor_series)  # Apply the Taylor series function for cos(-x)
)

# Plot the results using ggplot2
ggplot(data, aes(x)) +
  geom_line(aes(y = cos_x, color = "cos(x)"), size = 1) +      # Plot cos(x)
  geom_line(aes(y = cos_neg_x, color = "cos(-x)"), size = 1) + # Plot cos(-x)
  labs(title = "Comparison of Taylor Series for cos(x) and cos(-x)",
       x = "x (radians)",
       y = "Value",
       color = "Function") +
  theme_minimal() # Use a minimal theme for the plot
## Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
## ℹ Please use `linewidth` instead.
## This warning is displayed once every 8 hours.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.

#a plot showing two lines:

#one for the Taylor series 

#approximation of (\cos(x)) and the other 
#for (\cos(-x)). 

#If the identity (\cos(-x) = \cos(x)) holds,

# As these lines  overlap, providing a 
#visual confirmation of the identity.