Increase Precision of Numeric Calculations
By default, MATLAB® uses 16 digits of precision. For higher
precision, use the vpa
function
in Symbolic Math Toolbox™. vpa
provides variable
precision which can be increased without limit.
When you choose variable-precision arithmetic, by default, vpa
uses
32 significant decimal digits of precision. For details, see Choose Numeric or Symbolic Arithmetic. You can set
a higher precision by using the digits
function.
Approximate a sum using the default precision of 32 digits.
If at least one input is wrapped with vpa
, all
other inputs are converted to variable precision automatically.
vpa(1/3) + 1/2
ans = 0.83333333333333333333333333333333
You must wrap all inner inputs with vpa
,
such as exp(vpa(200))
. Otherwise, the inputs are
automatically converted to double by MATLAB.
Increase the precision to 50
digits by using digits
and
save the old value of digits
in digitsOld
.
Repeat the sum.
digitsOld = digits(50); sum50 = vpa(1/3) + 1/2
sum50 = 0.83333333333333333333333333333333333333333333333333
Restore the old value of digits for further calculations.
digits(digitsOld)
Note
vpa
output is symbolic. To use symbolic
output with a MATLAB function that does not accept symbolic values,
convert symbolic values to double precision by using double
.
Check the current digits
setting by calling digits
.
digits
Digits = 32
Change the precision for a single vpa
call
by specifying the precision as the second input to vpa
.
This call does not affect digits
. For example,
approximate pi
with 100
digits.
vpa(pi,100)
ans = 3.14159265358979323846264338327950288419716939937510582097494 4592307816406286208998628034825342117068
digits % digits remains 32
Digits = 32
Variable precision can be increased arbitrarily. Find pi
to 500
digits.
digitsOld = digits(500); vpa(pi) digits(digitsOld)
ans = 3.1415926535897932384626433832795028841971693993751058209749 445923078164062862089986280348253421170679821480865132823066 470938446095505822317253594081284811174502841027019385211055 596446229489549303819644288109756659334461284756482337867831 652712019091456485669234603486104543266482133936072602491412 737245870066063155881748815209209628292540917153643678925903 600113305305488204665213841469519415116094330572703657595919 530921861173819326117931051185480744623799627495673518857527 248912279381830119491
digits
and vpa
control
the number of significant decimal digits. For
example, approximating 1/111
with four-digit accuracy
returns six digits after the decimal point because the first two digits
are zeros.
vpa(1/111,4)
ans = 0.009009
Note
If you want to increase performance by decreasing precision, see Increase Speed by Reducing Precision.