# Set how many terms to generate
N <- 200

# Preallocate vectors
n <- 0:N
fib <- numeric(N + 1)
pell <- numeric(N + 1)

# Seed values
fib[1] <- 0  # F(0)
fib[2] <- 1  # F(1)

pell[1] <- 0 # P(0)
pell[2] <- 1 # P(1)


# Generate Fibonacci and Pell numbers using loops
for (i in 3:(N + 1)) {
  fib[i] <- fib[i - 1] + fib[i - 2]
  pell[i] <- 2 * pell[i - 1] + pell[i - 2]
}

# Combine into a DataFrame
pelldata <- data.frame(
  n = n,
  fib = fib,
  pell = pell
)

# View first few rows to confirm
head(pelldata, 10)






# Add rational approximation to sqrt(2)
approx_sqrt2 <- numeric(N + 1)

for (i in 1:(N + 1)) {
  if (fib[i] != 0) {
    approx_sqrt2[i] <- pell[i] / fib[i]
  } else {
    approx_sqrt2[i] <- NA  # Avoid division by zero for n = 0
  }
}

# Add to pelldata
pelldata$approx_sqrt2 <- approx_sqrt2

# View sample
head(pelldata, 10)






# Calculate the difference from sqrt(2) rounded to 5 decimal places
true_sqrt2 <- sqrt(2)
diff5 <- numeric(N + 1)

for (i in 1:(N + 1)) {
  if (!is.na(pelldata$approx_sqrt2[i])) {
    diff5[i] <- round(abs(pelldata$approx_sqrt2[i] - true_sqrt2), 5)
  } else {
    diff5[i] <- NA
  }
}

# Add to dataframe
pelldata$diff_5dp <- diff5

# View first few rows
head(pelldata, 10)








# Step 7: Accuracy = number of matching decimal places with sqrt(2)
acc_decimal <- numeric(N + 1)

true_str <- format(sqrt(2), digits = 16, nsmall = 16)

for (i in 1:(N + 1)) {
  if (!is.na(pelldata$approx_sqrt2[i])) {
    
    approx_str <- format(pelldata$approx_sqrt2[i], digits = 16, nsmall = 16)
    
    # Extract decimal part only (after '.')
    true_dec <- strsplit(true_str, "\\.")[[1]][2]
    approx_dec <- strsplit(approx_str, "\\.")[[1]][2]
    
    # Count matching decimal digits
    match_count <- 0
    for (j in 1:min(nchar(true_dec), nchar(approx_dec))) {
      if (substr(true_dec, j, j) == substr(approx_dec, j, j)) {
        match_count <- match_count + 1
      } else {
        break
      }
    }
    acc_decimal[i] <- match_count
  } else {
    acc_decimal[i] <- NA
  }
}

# Add to dataframe
pelldata$acc_decimals <- acc_decimal

# View sample
head(pelldata, 10)


