# Laurice Keogh
# March 2024
# Data Manipulation techniques investigated including the use of fibonacci, pell numbers, and approximation techniques. 




# Remove the scientific representation of long numbers for this R Session.
options(scipen = 999)


# TASK 1

# Create index vector.
index<-1:200
index

# Start the Fibonacci vector with the two start numbers specified in the assignment (0,1).
fib <- c(0, 1)
# For loop from position 3 to 200, following on from the two starting numbers.
for (i in 3:200) {
# Concatenate the Fibonacci vector with the formula to continue the sequence, which is the previous two numbers added together.
  fib <- c(fib, fib[i - 1] + fib[i - 2])
}


# Start the pell vector with the two start numbers specified in the assignment (0,1)
pell <- c(0, 1)
# For loop from position 3 to 200, following on from the two starting numbers.
for (i in 3:200) {
# Concatenate the pell vector with the formula to continue the sequence, which is the previous number multiplied by two, added to the previous number before that. 
  pell <- c(pell, pell[i - 1] * 2 + pell[i - 2])
}


# Creating the data frame and re-naming the columns.
pelldata <- data.frame(Index = index, Fibonacci = fib, Pell = pell)

#display the contents of pelldata
pelldata


# TASK 2

# Creating the Nth Approximation vector
Nth_Approximation <- numeric(199)
# For loop for up to 200 numbers.
for (i in 3:200) {
  # Calculating numbers based on the pell number in the previous position added to the pell number in the current position, then dividing this number by the pell number in the current position.
  # Formula based on (Pn-1+Pn)/Pn as specified in the assignment brief.
  Nth_Approximation[i] <- (pelldata$Pell[i - 1] + pelldata$Pell[i]) / pelldata$Pell[i]
}
# Appending the vector to the data frame
pelldata<-cbind(pelldata, Nth_Approximation)
# Display data frame
pelldata


# TASK 3

# Updating the data frame using a concatenated bind, naming the column, and using the Nth_Approximation data minus the square root to find the difference, then rounding the answer to 5 decimal places.
pelldata <- cbind(pelldata, squarerootdifference = round(abs(pelldata$Nth_Approximation - sqrt(2)), 5))
# Display data frame
pelldata


# Task 4 

# Create a new column in pelldata to hold the number of digits after the decimal place in the squarerootdifference.
# The following code changes to character and removes numbers before the decimal place. The answer is a count of the decimals
pelldata$Accuracy <- nchar(gsub(".*\\.", "", as.character(pelldata$squarerootdifference)))
# Display data frame.
pelldata