---
# System prepended metadata

title: Untitled

---

Portfolio 2;)


```{r}
square_n <- function(mu){
  delta <- 0.000001
  x <- 1
  
  while (abs(x^2 - mu) > delta) {
    x_n <- 0.5*(x + mu/x)
    x <- x_n
  }
  return(x)
  }

square_n(99)
```
This function, as opposed to the former function, allows for the user of the function to define where the algorithm begins (the x value). If the x-value is not defined it will default to 1, this default value can be changed in "function(mu, x = 1)" 
```{r}
square_n <- function(mu, x = 1){
  delta <- 0.0000001
  
  while (abs(x^2 - mu) > delta) {
    x_n <- 0.5*(x + mu/x)
    x <- x_n
  }
  
  return(x)
  }

square_n(16)
```
If you want to do some dataframes, like the one in the book, this function (sq_df) should do it. Just add the mu values (you want to find the square root of) to the vector k.

```{r}
sq_df <- function(mu, x = 1){
  delta <- 0.0000001
  u <- c(x)
  
  while (abs(x^2 - mu) > delta) {
    x_n <- 0.5*(x + mu/x)
    x <- x_n
    u <- append(u, x)
  }
  h <- u^2
  ex <- data.frame('x' = u, 'x^2' = h)
  return(ex)
}

k <- c(5, 16, 27, 51, 62, 99)
for (i in k) {
  g <- sq_df(i)
  print(g)
}
```


minor change in the last part here - but I made it so the end result of x will have a $$\pm$$ in front of it. Because x can both be negative and positive for the same solution of x^2 - i.e. the sqrt of 4 can both be -2 and 2. 
```{r}
sqrtsearcher <- function(mu, x = mu/2, delta = 1e-6){
  u <- c(x)
  
  while (abs(x^2 - mu) > delta) {
    x_new <- 0.5*(x + mu/x)
    x <- x_new
    u <- append(u, x)
  }
  h <- u^2
  latex <- '\u00B1'
  for (j in u) {
    p <- paste0(latex, u)
  }
  ex <- data.frame('x' = p, 'x^2' = h)
  return(ex)
}

# c) Creating a range of examples where the function systematic guesses its way to the value satisfying the delta value.
k <- c(25, 99, 1000, 25.7)
for (i in k) {
  g <- sqrtsearcher(i)
  print(g)
} 
```