## Matlab: increasing precision

Sometimes Matlab does not always perform as expected. This can be because of the IEEE 754 binary double precision floating point (double) representation used by Matlab: there is a finite number of digits to represent a number and this may not always be enough. We discuss how to use the Symbolic Toolkit to circumvent this.

Say you want to do this:

tau = 1.645553829408819e-05;

n = 1;

pb = 1-(1-tau)^n;

ps = n*tau*(1-tau)^(n-1);

Analytically, pb-ps would result in 1-(1-tau) – tau which equals zero. However:

>> pb-ps

ans =

1.409801637410057e-17

>> 1-(1-tau)^n - ps = n*tau*(1-tau)^(n-1)

ans =

1.409801637410057e-17

Needless to say, there’s an error here and depending on your application you may care. If you evaluate it by hand, it works out. This is because you perform symbolic calculations whereas Matlab does everything numerically. A solution to this challenge is using the Symbolic Toolkit.

tau = 1.645553829408819e-05;

n = 1;

syms n_sym tau_sym;

ps_sym = sym(n_sym*tau_sym*(1-tau_sym)^(n_sym-1));

pb_sym = sym(1-(1-tau_sym)^n_sym);

subs(pb_sym-ps_sym,{n_sym, tau_sym},{n,tau})

ans =

0

There, ain’t that pretty? First we define symbolic values for n and tau, then define our ps and pb. Then when we subtract ps_sym from pb_sym and substitute our real double values for their symbolic counterparts, we obtain the answer we are looking for.

Note however that the symbolic toolkit is quite slow compared to numerical calculations, your computation time may increase dramatically if you do this in an inner loop (however, the added precision may be worth it).

Please comment!