Matlab basic - how to get around floating point?

  • Context: MATLAB 
  • Thread starter Thread starter catsarebad
  • Start date Start date
  • Tags Tags
    Floating Matlab Point
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
catsarebad
Messages
69
Reaction score
0
i'm trying to learn MATLAB and as such i stumbled here while looking something up

http://www.mathworks.com/help/matlab/matlab_prog/floating-point-numbers.html

so the questions is

how does someone avoid something like

e = 1 - 3*(4/3 - 1) (this is example 1 in the webpage above)

not being zero

or this not being zero

sin(pi) (this is in example 1 again)


or this being zero
sqrt(1e-16 + 1) - 1 (in example 2)

thank you very much!
 
Physics news on Phys.org
Matlab is a numerical solver. If having a result like 1e-16 is not close enough to zero for you, you can increase the numerical accuracy that Matlab provides, at the cost of slowing computations down. If you really want exactly zero, use a symbolic calculation code like Mathematica or Maple. They do algebraic manipulations and evaluations the way you would do them in school.
 
This is a common problem. Just don't program any logic decisions based on equality of two real numbers. Always allow some tolerance when comparing two reals and apply the tolerance so that the safe decision will be made if the reals are within the tolerance.