2016-08-14 57 views
0

比方說f(x) = (4x^2-9)/(2x-3)。功能f(x)未定義在x=3/2。請注意,可以將該函數考慮爲產生f(x)=2x+3,但讓我們來檢查第一個等式。在下面的腳本時x=1.5,功能f(x=1.5)=4.0我面臨浮點問題嗎?

clear all 
clc 

x = 0:0.3:2; 

for i = 1:length(x) 
if x(i) == 1.5 % this line for some reasons is ignored. 
    y(i) = 6; 
else 
    y(i) = (4*x(i)^2-9)/(2*x(i)-3); 
end 
end 
x 
y 

上述腳本的輸出

x = 0   0.3000 0.6000 0.9000 1.2000 1.5000 1.8000 
y = 3.0000 3.6000 4.2000 4.8000 5.4000 4.0000 6.6000 

爲什麼y=4.0000x=1.5000?現在讓我們運行的代碼,而無需進行循環,

clear all 
clc 
x = 0:0.3:2 
y = (4*x.^2-9)/(2*x-3) 

上述代碼的結果是

x = 0  0.3000 0.6000 0.9000 1.2000 1.5000 1.8000 
y = 3.6000 

只有一個f(x)值。任何人都可以解釋發生了什麼?

回答

2

由於matrix division operator/,而不是你的第一個問題,是的,你正在運行到一個浮點精度誤差。您可以通過檢查x值的差值來檢查它是否應該是1.5和1.5。

x(6)-1.5 

%ans= 
%  -2.2204e-16 

具體地,在您的情況下,它來自使用0.3構建矢量x因爲該值不能被精確地保存到二進制,see here for a deeper explanation

以下任何的應解決問題

x=0:3:20;  %Create the vector based on values that can be represented 
x=x/10; 

x=[0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8]; %Directly input the values 

abs(x(i)-1.5) < tol %Instead of directly comparing values, compare the difference to a determined tolerance (very small compared to the values at hand) 

至於你的第二個問題@Phill已經給了你答案,你正在使用/矩陣劃分,並且你想要./元素明智的劃分。

0

當我用Octave中的for循環運行第一個示例時,我沒有看到x = 1.5 if語句被忽略的問題。也許這是Matlab和Octave之間的細微差別,雖然我會感到驚訝。

對於數組符號第二個例子

clear all 
clc 
x = 0:0.3:2 
y = (4*x.^2-9)/(2*x-3) 

你選擇的element by element division operator./