# TP2
## Exercice 2
### Question 1

```{r}
f <- function(x){
    return(exp(x) - 4*x)
}

f(1)
```

### Question 2

```{r}
curve(f, from = 0, to = 2.5)
abline(0, 0)
```

### Question 3

```{r}
dicho <- function(a, b, epsilon, f, Nmax) {
    n <- 0
    an <- a
    bn <- b
    xn <- (an+bn)/2
    while (abs(bn - an) > epsilon & n < Nmax) {
        if (f(an)*f(xn) < 0) {
            bn <- xn
        } else {
            an <- xn
        }
        xn <- (an + bn)/2
        n <- n+1
    }
    return (list("x"=xn, "n"=n))
}
```

### Question 4

```{r}
a <- 1
b <- 2.5
Nmax <- 100
epsilon <- 1e-8
result <- dicho(a, b,epsilon, f, Nmax)
result

curve(f, from = 0, to = 2.5)
abline(0, 0)
points(result$x, 0, col="red", pch=19)
```

### Question 5

```{r}
niterDicho <- function(a, b, epsilon) {
    y <- log((b - a)/epsilon, base = 2)
    return (ceiling(y))
}

niterDicho(a, b, epsilon)
```

### Question 6

```{r}
result$n
niterDicho(a, b, epsilon)
```

### Question 7

```{r}
dicthotomie2 <- function(a, b, epsilon, f, Nmax) {
    if (a >= b) {stop("a doit etre supérieur à b")}
    n <- 0
    an <- a
    bn <- b
    xn <- (an+bn)/2
    xn_hist <- c(xn)
    while (abs(bn - an) > epsilon & n < Nmax) {
        if (f(an)*f(xn) < 0) {
            bn <- xn
        } else {
            an <- xn
        }
        xn <- (an + bn)/2
        xn_hist <- append(xn_hist, xn)
        n <- n+1
    }
    if (n == Nmax) {
        stop("Attention: le nombre d'itérations maximal est atteint.")
    } else {
        message("La méthode converge après ", n, " itérations.")
    }
    return (list("x"=xn, "n"=n, "xn_hist"=xn_hist))
}
```

### Question 8

```{r}
a <- 1
b <- 2.5
Nmax <- 100
epsilon <- 1e-8
result_2 <- dicthotomie2(a, b, epsilon, f, Nmax)

error <- abs(result_2$xn_hist-result_2$x)
plot(1:result_2$n, (b-a)/2^(1:result_2$n), 
     type="l", log = "y", col="green")
lines(1:(result_2$n+1), error, type="l", col = "red")
```

## Exercice 3
### Question 1

```{r}
k0 <- 20
k1 <- 75
alpha  <- 1.5

D <- function(p){
  return(k0*(1+1/p))
}

O <- function(p){
  return(k1*p^alpha)
}

g <- function(p){
  return(k1*p^alpha - k0*(1+1/p))
}

curve(D, from = 0, to = 1)
curve(O, from = 0, to = 1, add = T) ## On utilise add = T pour ajouter à un plot existant.
```

### Question 2

```{r}
g <- function(p){
  return(k1*p^alpha - k0*(1+1/p))
}

a <- 0.2
b <- 1
epsilon <- 1e-15
Nmax <- 100

prix_eq <- dicthotomie2(a,b, epsilon, g, Nmax)
prix_eq$x
```