CroCo
CroCo

Reputation: 5741

Am I facing floating point issue?

Let's say f(x) = (4x^2-9)/(2x-3). The function f(x) is undefined at x=3/2. Note that the function can be factored to yield f(x)=2x+3 but let's examine the first equation. In the following script when x=1.5, the function 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

The output of the preceding script is

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

Why y=4.0000 when x=1.5000? Now let's run the code without for-loop,

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

The result of the above code is

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

There is only one value for f(x). Can any one explain what is going on?

Upvotes: 0

Views: 67

Answers (2)

Noel Segura Meraz
Noel Segura Meraz

Reputation: 2323

As for your first question, yes, you are running into a floating point precision error. You can check this by checking the difference between the x value that it's supposed to be a 1.5 and a 1.5.

x(6)-1.5

%ans=
%     -2.2204e-16

Specifically in your case it comes from using 0.3 to construct the vector x since that value cannot be precisely saved into binary, see here for a deeper explanation

Any of the following should solve your problem

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)

As for your second question @Phill already gave you the answer, you are using / matrix division, and you want ./ element wise division.

Upvotes: 2

Phil
Phil

Reputation: 1256

When I run your first example with the for loop in Octave, I do not see a problem with the x=1.5 if statement being ignored. Perhaps this is a subtle difference between Matlab and Octave for this although I would be surprised.

For the array notation second example

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

You have chosen the matrix division operator / instead of the element by element division operator ./

Upvotes: 0

Related Questions