# Unexpected inequality in Matlab

1. Feb 24, 2015

### hokhani

In the program below, the result of "difr" is not zero but according to the definition of qx in the second line, I expect it to be zero (because $qx^2+ky^2=(\frac{ef-u}{hbarv_f})^2$). What is the problem?
Code (Text):

ef=1;hbarv_f=658;ky=0.0011;u=2.5;
qx=sqrt(((ef-u)/hbarv_f)^2-ky.^2);
difr=(ef-u)/hbarv_f-sqrt(qx^2+ky^2)

2. Feb 24, 2015

### Staff: Mentor

You are not taking into account that $x = \sqrt{x^2}$ is only true when $x \ge 0$. (ef-u)/hbarv_f is negative.

3. Feb 24, 2015

### Staff: Mentor

I don't know MATLAB well, but isn't ^ a different operator than .^

4. Feb 24, 2015

### Staff: Mentor

The two operators act the same way on scalars. It is only for arrays that the behavior is different.

5. Feb 24, 2015

### hokhani

But this problem exists even if you put, for instance, ef=10!

6. Feb 24, 2015

### Staff: Mentor

No. Did you recalculate qx after having changed ef?

7. Feb 24, 2015

### hokhani

Yes, the result is:
Code (Text):

ef=10;hbarv_f=658;ky=0.0011;u=2.5;
qx=sqrt(((ef-u)/hbarv_f)^2-ky.^2);
difr=(ef-u)/hbarv_f-sqrt(qx^2+ky^2)

difr =

1.7347e-018

8. Feb 24, 2015

### Staff: Mentor

That's what I call zero. You are doing numerical computations: you have to allow for rounding errors. Look up floating-point arithmetic.

9. Feb 24, 2015

### hokhani

My program is sensitive even to this tiny value. What should I do to get rid of such errors?

10. Feb 24, 2015

### Staff: Mentor

You can't. You have to learn to deal with those errors. If the rest of your program is affected, it means that it is not properly written. For example, you should never compare the equality of two floating point numbers (or the equality of a float with an integer).

11. Feb 24, 2015

### hokhani

If I had in my program the fractions which take infinite values at some points, is it reasonable only putting eps (epsilon) in denominator or I must first factorize the "zero factor" out by trying (hardly in some cases) to change my equations (writing on paper) and then use them in the program?

Last edited: Feb 24, 2015