HW 1
HW 1
Homework 1
Due on Jan. 29, 2025
Problem 1 [3 pts]: Floating-point representation of numbers, and round-off error (Ref: Heath Chap. 1.3)
(1) Using any programming language/platform, check if the following equalities hold true. If not, explain why.
a. 𝑎𝑎 + 𝑏𝑏 + 𝑐𝑐 = 𝑎𝑎 + 𝑐𝑐 + 𝑏𝑏, where 𝑎𝑎 = 1, 𝑏𝑏 = 10−16 , 𝑐𝑐 = −1.
b. 0.3 + 0.6 = 0.9 (Check if it holds exactly, i.e., whether “0.3 + 0.6 == 0.9” is true or false.)
Hint: In Matlab, you can convert a number (“x”) to a character string using “num2str(x, 18)” to see all its digits.
(2) The following program is supposed to print “Launch!” on the screen at 𝑡𝑡 = 𝜋𝜋/2 (s) after the program starts.
(Suppose this is the optimal time to launch a rocket…)
Matlab: Python:
tic; import time, math
while true start_time = time.time()
elapsed_time = toc; while True:
if(elapsed_time == pi/2) elapsed_time = time.time() - start_time
disp("Launch!"); if elapsed_time == math.pi/2:
break; print("Launch!")
end break
end
Does this program do what it is supposed to do? If not, what could be done to fix the problem?
Problem 2 [5 pts]: For an iterative method, we define true relative error, 𝜖𝜖𝑡𝑡 , and approximate relative error, 𝜖𝜖𝑎𝑎 , at iteration
𝑘𝑘 (𝑘𝑘 = 0, 1, 2, … ) as
|𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐 𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 − 𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡 𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠| 𝑥𝑥𝑘𝑘+1 − 𝑥𝑥 ∗
𝜀𝜀𝑡𝑡 = =� �,
|𝑡𝑡𝑡𝑡𝑡𝑡𝑡𝑡 𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠𝑠| 𝑥𝑥 ∗
|𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐 𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎 − 𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝𝑝 𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎| 𝑥𝑥𝑘𝑘+1 − 𝑥𝑥𝑘𝑘
𝜀𝜀𝑎𝑎 = =� �.
|𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐𝑐 𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎𝑎| 𝑥𝑥𝑘𝑘+1
Consider function 𝑓𝑓(𝑥𝑥) = 𝑥𝑥𝑒𝑒 𝑥𝑥 − 2cos 𝑥𝑥.
(1) Apply the bisection method to find the root of 𝑓𝑓(𝑥𝑥) = 0 within interval (0, 1). Use (0, 1) as the initial bracketing
interval. Iterate until 𝜀𝜀𝑎𝑎 is less than 10−6. Show 𝜀𝜀𝑡𝑡 at each iteration — that is, plot 𝜖𝜖𝑡𝑡 vs. iteration number. (To get
the “true” solution, you may run the bisection method until 𝜀𝜀𝑎𝑎 is very small, say, less than 10−8.)
(2) Repeat (1) using the false-position (linear interpolation) method.
(3) For the same equation, 𝑓𝑓(𝑥𝑥) = 0, apply Newton’s method with an initial guess of 𝑥𝑥0 = 1, and the same stopping
criterion 𝜀𝜀𝑎𝑎 < 10−6. Again, plot 𝜀𝜀𝑡𝑡 vs. iteration number. Then, try initial guess 𝑥𝑥0 = −0.5, and explain your
result.
(4) Solve the same equation using the secant method. Try initial guess 𝑥𝑥0 = 0.0 and 𝑥𝑥1 = 1.0. Use the same stopping
criterion 𝜀𝜀𝑎𝑎 < 10−6.
Problem 3 [2 pts]: Prove that using the bisection method, the true error, |𝑥𝑥𝑘𝑘+1 − 𝑥𝑥 ∗ |, is always less than or equal to the
approximate error, |𝑥𝑥𝑘𝑘+1 − 𝑥𝑥𝑘𝑘 |, at any iteration.
Note: In practice, it is usually impossible to calculate the true error, because the true solution 𝑥𝑥 ∗ is unknown. Therefore,
what you have proven is a very nice feature of the bisection method.