-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMinimzing_With_condition_using_python.qmd
135 lines (84 loc) · 2.35 KB
/
Minimzing_With_condition_using_python.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
---
title: Minimizing a function with a condition
format: gfm
---
## Problem:
$$
\begin{aligned}
& f_X(x) = 12x^2 (1- x), \quad 0 < x < 1, \\
& A = \underset{b - a}{\min}\{(a, b)~|~\mathcal{P}(a < X < b) = 0.5\}\\
& \implies A = ?
\end{aligned}
$$
#### Soloution:
$$
\begin{aligned}
& X \sim \text{Beta}(3, 2), \\
& \mathcal{P}(a < X < b) = \int_a^b 12x^2 (1 - x) dx = \\
& 3(a^4 - b^4) + 4(b^3 - a^3) = 0.5 \implies \\
& \text{Using Lagrange Method:}\quad \gamma(a, b, \lambda) = b - a + \lambda \left[\int_a^b f(x)dx - 0.5\right] \implies \\
& (\hat{a}, \hat{b}): ~~ \begin{cases} \frac{\partial \gamma}{\partial \lambda} = 0 \\
\frac{\partial \gamma}{\partial a} = 0 \\
\frac{\partial \gamma}{\partial b} = 0\end{cases} \implies \\
& \begin{cases}3(a^4 - b^4) + 4(b^3 - a^3) = 0.5\\
b^2 - b^3 = a^2 - a^3 \end{cases}\quad \overset{\text{Using Numerical Method with python}}{\to}
\end{aligned}
$$
***
#### Using python
```{python}
import numpy as np
import sympy
from sympy import symbols, simplify, integrate, diff
x, a, b, l = symbols(['x', 'a', 'b', 'lambda'])
fx = 12 * x**2 * (1 - x)
ress = integrate(fx, (x, a, b))
ress
```
```{python}
gam = b - a + l * (ress - 0.5)
eq1 = diff(gam, l)
eq2 = diff(gam, a)
eq3 = diff(gam, b)
eq1
```
```{python}
eq2
```
```{python}
eq3
```
#### soloution
```{python}
from scipy.optimize import minimize
# Define the function to minimize
def func(x):
return x[1] - x[0]
# Define the constraint
cons = ({'type': 'eq', 'fun': lambda x: 3 * (x[0]**4 - x[1]**4) +
4 * (x[1]**3 - x[0]**3) - 0.5},
{'type': 'ineq', 'fun': lambda x: x[0] - 0},
{'type': 'ineq', 'fun': lambda x: x[1] - 0},
{'type': 'ineq', 'fun': lambda x: x[1] - x[0] - 0},
{'type': 'ineq', 'fun': lambda x: 1 - x[0] - 0},
{'type': 'ineq', 'fun': lambda x: 1 - x[1] - 0})
x0 = [0.75, 0.4]
# Call the minimize function with the method 'SLSQP' (Sequential Least Squares Programming)
res = minimize(func, x0, method = 'SLSQP', constraints = cons)
result = res.x
print(f"""
The solution is: \n\n
a: {result[0]}, \n
b: {result[1]}""")
```
## check soloution:
```{python}
round(integrate(fx, (x, result[0], result[1])), 6)
```
```{python}
a = result[0]; b = result[1]
print(f"""
a**2 - a**3: { round(a**2 - a**3, 6)}, \n
b**2 - b**3: { round(b**2 - b**3, 6)}
""")
```