---
title: "Component-1"
author: "Dharmik"
date: "2025-10-23"
output: html_document
---

```{r}
# Define the number of terms
n_terms <- 200

# Initialize vectors
n <- 0:(n_terms - 1)
fib <- numeric(n_terms)
pell <- numeric(n_terms)

# Set initial values
fib[1] <- 0; fib[2] <- 1
pell[1] <- 0; pell[2] <- 1

# Generate sequences
for (i in 3:n_terms) {
  fib[i] <- fib[i - 1] + fib[i - 2]
  pell[i] <- 2 * pell[i - 1] + pell[i - 2]
}

# Create the initial dataframe
pelldata <- data.frame(
  n = n,
  Fibonacci = fib,
  Pell = pell
)

# Print the first 15 rows
print(head(pelldata, 15))
```
```{r}
# Calculate the approximation of sqrt(2)
# Formula: 1 + P_{n-1} / P_n
pell_lagged <- c(NA, pelldata$Pell[-n_terms])
pelldata$Sqrt2_Approx <- 1 + pell_lagged / pelldata$Pell

# Print the first 15 rows of the updated dataframe
print(head(pelldata, 15))

```

```{r}
# Calculate the difference from the actual sqrt(2)
actual_sqrt2 <- sqrt(2)
pelldata$Diff_from_sqrt2 <- round(pelldata$Sqrt2_Approx - actual_sqrt2, 5)

# Print the first 15 rows of the updated dataframe
print(head(pelldata, 15))

```


```{r}
# Function to count matching decimal places
count_decimal_accuracy <- function(approx_val, true_val, digits = 15) {
  if (is.na(approx_val)) return(NA_integer_)
  
  approx_str <- formatC(approx_val, digits = digits, format = "f")
  true_str   <- formatC(true_val,   digits = digits, format = "f")
  
  # Get characters after the decimal point
  approx_chars <- strsplit(substr(approx_str, 3, nchar(approx_str)), "")[[1]]
  true_chars   <- strsplit(substr(true_str,   3, nchar(true_str)), "")[[1]]
  
  # Find the index of the first mismatch
  first_mismatch <- which(approx_chars != true_chars)[1]
  
  if (is.na(first_mismatch)) {
    return(length(true_chars)) # All match
  } else {
    return(first_mismatch - 1) # Number of matches before the mismatch
  }
}

# Apply the function
pelldata$Accuracy_DP <- sapply(pelldata$Sqrt2_Approx,
                               count_decimal_accuracy,
                               true_val = actual_sqrt2)

# Print the first 15 rows of the final dataframe
print(head(pelldata, 15))

```

