Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Unexpected inequality in Matlab

  1. Feb 24, 2015 #1
    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 [itex]qx^2+ky^2=(\frac{ef-u}{hbarv_f})^2[/itex]). 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. jcsd
  3. Feb 24, 2015 #2

    DrClaude

    User Avatar

    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.
     
  4. Feb 24, 2015 #3

    Dale

    Staff: Mentor

    I don't know MATLAB well, but isn't ^ a different operator than .^
     
  5. Feb 24, 2015 #4

    DrClaude

    User Avatar

    Staff: Mentor

    The two operators act the same way on scalars. It is only for arrays that the behavior is different.
     
  6. Feb 24, 2015 #5
    But this problem exists even if you put, for instance, ef=10!
     
  7. Feb 24, 2015 #6

    DrClaude

    User Avatar

    Staff: Mentor

    No. Did you recalculate qx after having changed ef?
     
  8. Feb 24, 2015 #7
    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
     
  9. Feb 24, 2015 #8

    DrClaude

    User Avatar

    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.
     
  10. Feb 24, 2015 #9
    My program is sensitive even to this tiny value. What should I do to get rid of such errors?
     
  11. Feb 24, 2015 #10

    DrClaude

    User Avatar

    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).
     
  12. Feb 24, 2015 #11
    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
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook