0

I have MATLAB code:

clear all;
clc;
a=-sqrt(2);
b=sqrt(2);
N=10;
h=(b-a)/N;
x=a:h:b;
f=sqrt(2-x.^2);

If I run this code in MATLAB 2017a, then I have

  Columns 1 through 3

   0.0000 + 0.0000i   0.8485 + 0.0000i   1.1314 + 0.0000i

  Columns 4 through 6

   1.2961 + 0.0000i   1.3856 + 0.0000i   1.4142 + 0.0000i

  Columns 7 through 9

   1.3856 + 0.0000i   1.2961 + 0.0000i   1.1314 + 0.0000i

  Columns 10 through 11

   0.8485 + 0.0000i   0.0000 + 0.0000i

Since f=sqrt(2-x.^2) for -sqrt(2) to sqrt(2) is real number it should not be complex number. Why the result is appearing imaginary part? How to fix it?

  • 1
    As you've no doubt figured out, `2-sqrt(2).^2` is `-4.4409e-16`. This is a floating-point rounding error (as discussed in the linked Q&A). You can avoid this issue in this particular case by rounding to 15 digits: `f=sqrt(round(2-x.^2,15))`. – Cris Luengo Jul 14 '21 at 05:59

0 Answers0