Matlab 教材:用 Matlab 認識邏輯分岔

前面以 for 迴圈為例,看過迭代概念。現在講另一種程式語言內基礎的結構: 邏輯分岔。其最常見結構是

if (True_or_False), 計算, end
其中 True_or_False 的部份,是一個純量 (scalar),只要那個數值不是 0, 就被 Matlab 視為 True;只有當它是 0 才會被 Matlab 視為 False。 雖然如此,一般實用的時候,在 True_or_Flase 那裡都會寫一個邏輯語句 (logical expression),也就是一個關於邏輯算子的計算。 邏輯算子認為 True 的時候,答案是 1,認為 Flase 的時候,答案是 0。

如果 True_or_False 那裡是 True,則就會執行「計算」,否則不做。 所謂「計算」不一定只有一個指令,可以有很多,用逗點 , 或分號 ; 隔開, 一直計算到 end 為止。如果一個計算指令用逗點 , 結束,那麼它的計算結果會顯示出來。 如果一個計算指令用分號 ; 結束,那麼 Matlab 就「默默地」執行計算。 這些都是在學習 for 迴圈的時候知道的。

舉個無聊的例子吧:

if (Inf > 1), disp('infinity is larger than one'); end
你應該會看到 Matlab 回應一句正確的句子:infinity is larger than one。 如果改成
if (Inf > Inf), disp('infinity is larger than infinity'); end
那 Matlab 就不上當,他沒有任何反應。

如果條件不成立的時候,也要 Matlab 做點別的事,那就要用以下語法:

if (True_or_False), 計算, else, 不然計算, end
如果 True_or_False 部份是 True,那就執行「計算」一直到 else 為止。 如果 True_or_False 部份是 False,那就執行「不然計算」一直到 end 為止。 延續上面的無聊例子,可以說
if (Inf > 1), disp('infinity is larger'); else, disp('infinity is not larger'); end
執行之後應該看到 Matlab 輸出一句話 infinity is larger。 不過,這一句指令似乎太長了。其實 Matlab 不在乎我們把它寫成兩行,例如:
if (Inf > 1), disp('infinity is larger');
else, disp('infinity is not larger'); end
事實上,如果您寫了 if 那麼 Matlab 就會等待 end。 如果您開始了 if 而沒有寫 end,那 Matlab 就不會執行,因此就不會出現提示號 >>。將以下三列、一列一列地輸入 Matlab 試試看:
if (Inf > 1), disp('infinity is larger');
else, disp('infinity is not larger');
end

我們還可以試試看

if (Inf == Inf), disp('infinities are equivalent');
else, disp('infinities are not the same'); end
Matlab 的回答代表了計算機內部對於「無限大」的看法, 不一定和數學老師說的一樣。

我們曾經說過,比較兩個浮點數是否相等是很「危險」的。 在 [數值計算無可避免的誤差] 裡面,我們學到了一些。 現在再來一遍。問 Matlab

x = 1/7;
if (7*x == 1), disp('Bingo'); else, disp('Hee hee hee'); end
再試試看
x = 1/7;
if (x+x+x+x+x+x+x == 1), disp('Bingo'); else, disp('Hee hee hee'); end
但是,如果用恰當的形式詢問,就會正確了。例如
x = 1/7;
if (abs(1-x-x-x-x-x-x-x) <= 5e-15), disp('Bingo');
else, disp('Hee hee hee'); end

習題

  1. 若 x = 1/7; Matlab 認為 (3*x + 4*x) 是否等於 1?
  2. 若 x = 1/7; Matlab 認為 (2*x + 5*x) 是否等於 1?
  3. 用十進制科學數字表示法寫出 5e-15。
  4. Matlab 把 Inf + Inf 的答案視為 True 還是 False?還是兩者皆非? 您認為它這樣的處理,是否正確?
  5. 按照您在數學課學到的知識,Inf - Inf 應該是什麼? 而 Matlab 的計算結果是什麼? 您如何解釋這個現象?
  6. Matlab 把 Inf - Inf 的答案視為 True 還是 False?還是兩者皆非? 您認為它這樣的處理,是否正確?
[BCC16-B]
單維彰 (2003/04/20) ---
[Prev] [Next] [Up]