##Understand the difference between exact and approximate (Real) numbers
Unlike many other computational software, Mathematica allows you to deal with exact integers and rational numbers (heads Integer
and Rational
), as well as normal floating-point (Real
) numbers. While you can use both exact and floating-point numbers in a calculation, using exact quantities where they aren’t required can slow computations down.
Also, mixing the data types up in a single list will mess up packed arrays.
The different data types are represented differently by Mathematica. This means, for example, that integer zero (0
) and real zero (0.
) only equal numerically (0 == 0.
yields True
) but not structurally (0 === 0.
yields False
). In certain cases you have to test for bothyou have to test for both or you will run into trouble. And you have to make sure that List
index numbers (i.e. the arguments to Part
) are exact integers not real numbersexact integers not real numbers.
As with any computer language, calculations with real numbers is not exact and will accumulate error. As a consequence, your real-valued calculation might not necessarily return zero even when you think it should. There may be small (less than $10^{-10}$) remainders, which might even be complex valued. If so, you can use Chop
to get rid of these. Furthermore, you can carry over the small numerical error, unnoticed:
Floor[(45.3 - 45)*100] - 30 (* ==> -1 instead of 0 *)
In such cases, use exact rational numbers instead of reals:
Floor[(453/10 - 45)*100] - 30 (* ==> 0 *)
Sometimes, if you are doing a calculation containing some zeros and some approximate real numbers, as well as algebraic expressions, you will end up with approximate zeros multiplied by the algebraic elements in the result. But of course you want them to cancel out, right? Again, use Chop
, that removes small real numbers close to zero (smaller than $10^{-10}$ according to the default tolerance level).
Some solvers (Solve
, Reduce
, Integrate
, DSolve
, Minimize
, etc.) try to find exact solutions. They work better with exact numbers for coefficients and powers. As just mentioned, if approximate real numbers are used, terms that should cancel out might not, and the solver might fail to find a solution. Other solvers (NSolve
, FindRoot
, NIntegrate
, NDSolve
, NMinimize
, FindMinimum
, etc.) try to find approximate solutions. Generally they work well with either exact or approximate numbers. However, some of them do symbolic analysis and sometimes perform better with functions or equations that are given in terms of exact numbers.
keywords: real integer number-type machine-precision