# Monte Carlo 


```julia
using Plots
```

## Tetrahedron volume


$$
\begin{align}
V &= \int_0^1{\int_0^{1-x}{\int_0^{1-x-y}{1 \quad dz}dy}dx} \\
&= \int_0^1{\int_0^{1-x}{1-x-y \quad dy}dx} \\
&= \int_0^1{ \left( y(1-x)-\frac{y^2}{2} \right)_{y=0}^{y=1-x} \quad dx} \\
&= \int_0^1{ \frac{(1-x)^2}{2} \quad dx} \\
&= \int_0^1{ \frac{1-2x+x^2}{2} \quad dx} \\
&= \left( \frac{x}{2} - \frac{x^2}{2} + \frac{x^3}{6} \right)_{x=0}^{x=1} \\
&= \frac{1}{6}
\end{align}
$$

## Standard Monte Carlo integration


```julia
function montecarlo(iterations)
    integral = 0
    for i=1:iterations
        x, y, z = rand(3)
        if (x+y+z<1)
            integral += 1
        end
    end
    volume = integral/iterations
end

montecarlo(100)
```




    0.16



# Test


```julia
function montecarlotest(iterations)
    err = log10(abs(montecarlo(iterations)-1/6))
end
```




    montecarlotest (generic function with 1 method)




```julia
p = plot()
for i=1:10
    x = 1:7
    y = montecarlotest.(10 .^x)
    p = scatter!(p, x, y, label=:false)
end

display(p)
```


    

    


## Adjourn


```julia
using Dates
println("mahdiar")
Dates.format(now(), "Y/U/d HH:MM")  
```

    mahdiar





    "2021/April/17 16:17"



868034198ea122f50dd67f2415fad1ff63a99bb4
ipynb
Jupyter Notebook
HW12/2.ipynb
mahdiarsadeghi/NumericalAnalysis
95a0914c06963b0510971388f006a6b2fc0c4ef9
MIT
HW12/2.ipynb
mahdiarsadeghi/NumericalAnalysis
95a0914c06963b0510971388f006a6b2fc0c4ef9
MIT
HW12/2.ipynb
mahdiarsadeghi/NumericalAnalysis
95a0914c06963b0510971388f006a6b2fc0c4ef9
MIT
Qwen/Qwen-72B
1. YES
2. YES