0

I'm trying to create a Euler approximation function in MATLAB. I am supposed to evaluate at t = 0.1, 0.2, 0.3, 0.4 but for some reason my code does not evaluate at 0.3.

Here is my code:

clear; clc;
stepSizes = [0.1 0.05 0.025];
tInitial = 0;
yInitial = 1;
t = tInitial;
y = yInitial;

for step = 1:3
    stepSize = stepSizes(step);
    for tVal = 0:stepSize:0.4;
        slope = 3+t-y;
        yVal = y + slope*(tVal-t);
        fprintf('%0.3f\n',tVal);
        if tVal==0.1 || tVal==0.2 || tVal==0.3 || tVal==0.4
            fprintf('Stepsize: %0.3f, tVal = %0.3f, yVal = %0.3f.\n',...
                stepSize, tVal, yVal);
        end
        t = tVal;
        y = yVal;
    end
end

Here is some of my printed output that illustrates my problem. All the values are match the answers I obtained while doing it by hand.

0.000
0.100
Stepsize: 0.100, tVal = 0.100, yVal = 1.200.
0.200
Stepsize: 0.100, tVal = 0.200, yVal = 1.390.
0.300
0.400
Stepsize: 0.100, tVal = 0.400, yVal = 1.744.

Why is the logical equals for tVal ==0.3 not working?

Daniel
  • 36,610
  • 3
  • 36
  • 69
user3642365
  • 549
  • 1
  • 6
  • 16

2 Answers2

4

You are using floating points. 3*0.1 is not equal to 0.3 when using floats.

What Every Computer Scientist Should Know About Floating-Point Arithmetic

Check with tolerance abs(tVal-.3)<eps for a simple workaround.

Daniel
  • 36,610
  • 3
  • 36
  • 69
0

You can also fix the loop increments with round and test against the true values

for tVal = round( (0:stepSize:0.4)*1000 )/1000 
    if tVal==0.1 || tVal==0.2 || tVal==0.3 || tVal==0.4
marsei
  • 7,691
  • 3
  • 32
  • 41