---
# System prepended metadata

title: Methods 2 -- Portfolio Assignment 2

---

---
title: "Methods 2 -- Portfolio Assignment 2"
author: "Julie Bang Mikkelsen, AU718507"
date: "`r format(Sys.Date(), '%B %d, %Y')`"
output:
  pdf_document: default
  html_document:
    df_print: paged
---

- *Type:* Individual assignment
- *Due:* 10 April 2022, 23:59

```{r include = FALSE}
#Loading packages
library(pacman)
pacman::p_load(tidyverse, pastecs, stringr, dplyr, knitr, kableExtra)
```


## 1. Square root function

My function finds the squareroot of a given positive number, $\mu$, by finding the root of $f(x) = x^2 - \mu = 0$. I improve my guess with the Newton-Raphson method of defining $x_{j+1} = x_j - \frac{f(x_j)}{f'(x_j)}$ until the guess squared, $x^2$, is so close to the true $\mu$, that their difference, the "error", is below a specified threshold. I call this "limit".

According to Gill, p. 249, I can insert $f(x)$ and $f'(x)$ into the function and get:

\begin{align*}
    x_{j+1} = x_j - \frac{x_j^2 - \mu}{2x_j} = \frac{1}{2}(x_j+\mu x_j^{-1})
\end{align*}

Now I can insert this function into a while loop, that keeps running as long as the difference between $x^2$ and $\mu$ is above the limit. For each iteration, I also print $x$ and $x^2$ to a dataframe for niceness. I set my limit to .05, because it is equivalent to that of statistical significance. I choose $x_0=\mu/2$ as my initial guess because this is halfway between $0$ and $\mu$, which are both obviously wrong.

```{r}
my_fun <- function(mu){
  x <- mu/2 # Defining starting point, x_0
  limit <- .05 # Defining an acceptable precision threshold
  error <- abs(x^2-mu) #Defining the error of the current guess, x_j
  iter <- 1 # Defining iteration number for niceness
  
  # Creating a dataframe for x and x^2 results for each iteration
  results_df <- data.frame(iteration = iter, x_value = x, x_sq = x^2)
  
  while (error > limit){
    x <- (0.5*(x+mu/x))
    error <- abs(x^2-mu)
    iter <- iter + 1
    
    # Appending new row to dataframe
    results_df <- rbind(results_df, data.frame(iteration = iter, x_value = x, x_sq = x^2))
    }
    
    # Printing results dataframe as html table
    return(
      results_df %>%
        kbl(caption = "Results table") %>%
        kable_classic(full_width = F, html_font = "Cambria") %>%
        kable_styling(latex_options = "HOLD_position")
    )
  }
```

### Examples

```{r}
my_fun(16) # See Table 1
my_fun(90) # See Table 2
my_fun(356) # See Table 3
```

When applied to negative numbers, my function will continue running and never stop. This happens because when $\mu$ is negative, the error will become the sum of, instead of the difference, between $x^2$ and $\mu$, with the result, that the error will never become smaller than the limit, and the while loop wont ever be broken. Therefore, my function only works on positive numbers.
\newpage