Professional Documents
Culture Documents
For Loop: Quang-Vinh Dinh Ph.D. in Computer Science
For Loop: Quang-Vinh Dinh Ph.D. in Computer Science
Quang-Vinh Dinh
Ph.D. in Computer Science
Year 2021
For Loop
keyword semicolon Code before for
Init Statement
false
Expression
printf(“%d \n”, i);
true
Expression
Code after for
Year 2021 Updating Statement 1
For Loop
Code before for
Init Statement
true
Updating Statement
true
𝑖 = 𝑖 + 1;
↔ 𝑖 + +; Code inside for
𝑖 = 𝑖 − 1;
↔ 𝑖 − −;
Updating Statement
true
𝑖 = 𝑖 + 1;
↔ 𝑖 + +; Code inside for
𝑖 = 𝑖 − 1;
↔ 𝑖 − −;
Updating Statement
Bad code!!!
Code after for
Year 2021 4
For Loop
Code before for
Cumulative function
𝑛
Init Statement
𝐶 = 𝑘
𝑘=0
false
𝑛 is a natural number; 𝑛 ∈ ℕ Expression
true
𝑖 = 𝑖 + 1;
↔ 𝑖 + +; Code inside for
𝑖 = 𝑖 − 1;
↔ 𝑖 − −;
Updating Statement
Bad code!!!
Code after for
Year 2021 5
For Loop
Code before for
Cumulative function
𝑛
Init Statement
𝐶 = 𝑘
𝑘=0
false Using i--
𝑛 is a natural number; 𝑛 ∈ ℕ Expression
true
𝑖 = 𝑖 + 1;
↔ 𝑖 + +; Code inside for
𝑖 = 𝑖 − 1;
↔ 𝑖 − −;
Updating Statement
𝑋 = {𝑋1 , … , 𝑋𝑁 } 𝑋 = {2, 8, 5, 4, 1, 8}
𝑁=6
Formula 𝑁
1 1
𝑁 𝜇 = 𝑋𝑖 = 2 + 8 + 5 + 4 + 1 + 8
1 𝑁 6
𝜇 = 𝑋𝑖 𝑖−1
𝑁 18
𝑖−1 = =3
6
Year 2021 7
For Loop
break keyword
Code before for
Init Statement
false
Expression
true
break
Code inside for
printf(“%d \n”, i);
Updating Statement
Init Statement
false
Expression
true
continue
Code inside for
printf(“%d \n”, i);
Updating Statement
Gregory-Leibniz Series
𝑛
−1 𝑖+1
𝑃𝐼 ≈ 4
2𝑖 − 1
𝑖=1
Year 2021 10
Example
PI estimation
Nilakantha Series
𝑛
−1 𝑖
𝑃𝐼 ≈ 3 + 4
2𝑖 + 2 2𝑖 + 3 2𝑖 + 4
𝑖=0
Year 2021
Example
Euler's number
𝑒 = 2.71828
1) Compute factorial
2) Estimate e
Formula
Year 2021 12
6
Example
Euler's number
1) Compute factorial
2) Estimate e
Year 2021 13
7
Example: Quadratic Root
Compute quadratic root for the number N
𝑁=9
9
𝑠𝑒𝑡 𝑥0 = = 4.5
Newton Method 2
Compute 9
𝑛=0
Set a value for 𝑥0 ; n = 0
(𝑥0 = N/2)
𝑛=0
𝑁 9
𝑥0 + 𝑥 4.5 +
𝑥1 = 0
= 4.5 = 6.5 = 3.25
𝑁 2 2 2
𝑥𝑛 +
𝑥𝑛
𝑥𝑛+1 = 𝑛=1
𝑁
2 𝑥1 + 𝑥 3.25 +
9
𝑥2 = 1
= 3.25 = 6.019 = 3.009
2 2 2
n=n+1 𝑛=2
𝑁 9
𝑥2 + 𝑥 3.009 + 3.009
2
𝑥3 = = = 3.00001
2 2
Year 2021 14
4
Example: Quadratic Root
Compute quadratic root
for the number N
Newton Method
𝑁
𝑥𝑛 +
𝑥𝑛
𝑥𝑛+1 =
2
n=n+1
Overflow and Underflow
Softmax function
Input Probability
0 ≤ 𝑓 𝑧𝑖 ≤ 1
Input Probability
𝑓 𝑧𝑖 = 1
𝑖
𝑧1 = 1.0 𝑓(𝑧1 ) = 0.09
𝑧2 = 2.0 Softmax 𝑓(𝑧2 ) = 0.24
𝑧3 = 3.0 𝑓(𝑧3 ) = 0.67
Year 2021 16
7
Implementation
(straightforward)
Softmax function
Convert a vector of real numbers to a vector of probabilities
Formula
𝑥𝑖 Input Probability
𝑒
𝑓 𝑥𝑖 =
σ𝑗 𝑒 𝑥𝑗 𝑥1 = 1.0 𝑓(𝑥1 ) = 0.09
0 ≤ 𝑓 𝑥𝑖 ≤ 1 𝑥2 = 2.0 Softmax 𝑓(𝑥2 ) = 0.24
𝑒𝑥
The function increases
rapidly as x increases
𝑥 ∈ [0, +∞)
𝑒 𝑥 ∈ [1, +∞)
17
8
Implementation
(stable)
Softmax function (stable)
(Stable) Formula Probability
X X-m
𝑚 = max(𝒙) 𝑥1 = 1.0 𝑥1 = −2.0 𝑓(𝑥1 ) = 0.09
𝑒 (𝑥𝑖−𝑚) 𝑥2 = 2.0 𝑥2 = −1.0 Softmax 𝑓(𝑥2 ) = 0.24
𝑓 𝑥𝑖 =
σ𝑗 𝑒 (𝑥𝑗 −𝑚) 𝑥3 = 3.0 𝑥3 = 0 𝑓(𝑥3 ) = 0.67 Why???
𝑒𝑥
𝑥 ∈ (−∞, 0)
𝑒 𝑥 ∈ (0, 1)
18
9