Unexpected inequality in Matlab

  • Context: MATLAB 
  • Thread starter Thread starter hokhani
  • Start date Start date
  • Tags Tags
    Inequality Matlab
Join the discussion
Ask a follow-up here, or get your own question answered by working scientists, mathematicians and engineers — people, not an autocomplete.
Real named experts · corrections over time · the nuance an AI answer skips
10 replies · 2K views
hokhani
Messages
608
Reaction score
22
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:
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)
 
Physics news on Phys.org
You are not taking into account that ##x = \sqrt{x^2}## is only true when ##x \ge 0##. (ef-u)/hbarv_f is negative.
 
DaleSpam said:
I don't know MATLAB well, but isn't ^ a different operator than .^
The two operators act the same way on scalars. It is only for arrays that the behavior is different.
 
DrClaude said:
You are not taking into account that ##x = \sqrt{x^2}## is only true when ##x \ge 0##. (ef-u)/hbarv_f is negative.
But this problem exists even if you put, for instance, ef=10!
 
hokhani said:
But this problem exists even if you put, for instance, ef=10!
No. Did you recalculate qx after having changed ef?
 
DrClaude said:
No. Did you recalculate qx after having changed ef?
Yes, the result is:
Code:
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
 
DrClaude said:
That's what I call zero. You are doing numerical computations: you have to allow for rounding errors. Look up floating-point arithmetic.
My program is sensitive even to this tiny value. What should I do to get rid of such errors?
 
hokhani said:
My program is sensitive even to this tiny value. What should I do to get rid of such errors?
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).
 
DrClaude said:
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).
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: