# Solve a nonlinear system
\begin{align}
3x_1 - \cos(x_2x_3) - \frac{1}{2}& = 0\\
x_1^2 - 81(x_2+0.1)^2 + \sin(x_3) +1.06& = 0\\
e^{-x_1x_2} + 20 x_3 + \frac{10\pi-3}{3}& = 0
\end{align}



```julia
using Printf
using ForwardDiff
using LinearAlgebra
using NLsolve
```

## Hand Coded Jacobian


```julia
function F(x)
    return [3*x[1] - cos(x[2]*x[3]) - 0.5
            x[1]^2 - 81 * (x[2]+0.1)^2 + sin(x[3])+1.06
            exp(-x[1]*x[2]) + 20 * x[3] + (10 * π-3)/3];
end


function J(x)
    J_ = zeros(3,3);
    J_[1,1] = 3;
    J_[1,2] = x[3] * sin(x[2]*x[3]);
    J_[1,3] = x[2] * sin(x[2]*x[3]);    
    
    J_[2,1] = 2*x[1];
    J_[2,2] =-162 * (x[2]+0.1);
    J_[2,3] = cos(x[3]);
    
    J_[3,1] = -x[2] * exp(-x[1]*x[2]);
    J_[3,2] = -x[1] * exp(-x[1]*x[2])    
    J_[3,3] = 20;
    return J_
end
```


```julia
F(zeros(3))
```


```julia
J([0., 0., 0.])
```


```julia
# starting guess
x = zeros(3);
δ = zeros(3);
n_iters = 20;
tol = 1e-10;

for n in 1:n_iters
    δ .= -J(x)\F(x);
    @. x += δ;
    f_err = norm(F(x));
    @printf("%d: ||F(x)|| = %g\n",n, f_err);
    
    if(f_err<tol)
        break;
    end
end
@show x;

```

## Automatic Differentiation


```julia
J_auto = x-> ForwardDiff.jacobian(F, x);
```


```julia
J_auto(x)
```


```julia
# starting guess
x = zeros(3);
δ = zeros(3);
n_iters = 20;
tol = 1e-10;

for n in 1:n_iters
    δ .= -J_auto(x)\F(x);
    @. x += δ;
    f_err = norm(F(x));
    @printf("%d: ||F(x)|| = %g\n",n, f_err);
    
    if(f_err<tol)
        break;
    end
end
@show x;

```

## Solution with NLsolve


```julia
x = zeros(3);
soln= nlsolve(F, x)
```


```julia
x = zeros(3);
soln= nlsolve(F,J_auto, x)
```

05e8026f35ae126fbcc40ab7d1562c64afdaf6b1
ipynb
Jupyter Notebook
notebooks/Julia Functionality/Multidim Roots.ipynb
liamfdoherty/Math_300_2021
815487d4fe6549026fcd4c3efea152c723457129
MIT
2021-09-20T02:43:59.000Z
2022-01-23T19:09:21.000Z
notebooks/Julia Functionality/Multidim Roots.ipynb
liamfdoherty/Math_300_2021
815487d4fe6549026fcd4c3efea152c723457129
MIT
notebooks/Julia Functionality/Multidim Roots.ipynb
liamfdoherty/Math_300_2021
815487d4fe6549026fcd4c3efea152c723457129
MIT
2021-09-22T15:34:13.000Z
2021-12-03T11:11:55.000Z
Qwen/Qwen-72B
1. YES
2. YES