MATLAB Matlab basic - how to get around floating point?

AI Thread Summary
When learning MATLAB, users often encounter issues with floating-point arithmetic, leading to unexpected results such as non-zero outputs for expressions that should theoretically equal zero. For instance, calculations like e = 1 - 3*(4/3 - 1) and sin(pi) can yield results that are not exactly zero due to the limitations of numerical precision in floating-point representation. To mitigate these issues, increasing MATLAB's numerical accuracy can help, although it may slow down computations. For exact results, using symbolic computation tools like Mathematica or Maple is recommended, as they handle algebraic manipulations more precisely. It is also advised to avoid programming logic based on the exact equality of real numbers; instead, implementing a tolerance level when comparing values can lead to safer and more reliable outcomes.
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.
 
Last edited by a moderator:
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.
 
Back
Top