### Symbolic expressions,variable precision and exact arithmatic in MATLAB

Symbolic Expressions, Variable Precision, and Exact Arithmetic

As we have noted,MATLAB uses floating point arithmetic for its calculations.

Using theSymbolic Math Toolbox,you can also do exact arithmetic with symbolic expressions. Consider the following example:

>> cos(pi/2)

ans =

6.1232e-17

17

The answer is written in floating point format and means 6.1232×10-17 .

However, we know that cos(p/2) is really equal to 0. The inaccuracy is due

to the fact that typing pi in MATLAB gives an approximation to pi accurate

to about 15 digits, not its exact value. To compute an exact answer, instead

of an approximate answer, we must create an exact symbolic representation

of p/2 by typing sym(’pi/2’). Now let’s take the cosine of the symbolic

representation of p/2:

>> cos(sym(’pi/2’))

ans =

0

This is the expected answer.

The quotes around pi/2 in sym(’pi/2’) create a string consisting of the

characters pi/2 and prevent MATLAB from evaluating pi/2 as a floating

point number.The command sym converts the string to asymbolic expression.

The commands sym and syms are closely related. In fact, syms x is equiv-

alent to x = sym(’x’). The command syms has a lasting effect on its argu-

ment (it declares it to be symbolic from now on), while sym has only a tempo-

rary effect unless you assign the output to a variable, as in x = sym(’x’).

Here is how to add 1/2 and 1/3 symbolically:

>> sym(’1/2’) + sym(’1/3’)

ans =

5/6

Finally,you can also dovariable-precision arithmetic with vpa.For example,

v

to print 50 digits of 2, type

>> vpa(’sqrt(2)’, 50)

ans =

1.4142135623730950488016887242096980785696718753769

## 0 comments:

Post a Comment