MATLAB: How to apply vpa function for all codes in the editor page , without writing it each time

vpa

% When I start to write any codes, I wanna determine precision which I need, so I need to apply vpa function before writing any codes and calculations, like format long.

Best Answer

You can use the digits function to set the number of digits of precision when it is doing fixed point calculation. When it is doing calculations on rationals that will yield rational answers, digits will not have any effect.
When a numeric value is copied from the MATLAB level to the MuPAD level, the numeric value is converted to rational. For example,
syms A B
A * 2.18 + B^1.1
would reach MuPAD as
A * 109/50 + B^(11/10)
And then the rule about working with rationals applies. Values that look floating point at the MATLAB level do not stay floating point (or fixed point) when they get to MuPAD.
You can, however, force MuPAD to treat a numeric value as fixed point or floating point. See the documentation for syms. The applicable examples there are
digits(10), sym(4/3,'d') is 1.333333333
and
sym(1/10,'f') is 3602879701896397/36028797018963968
Values created as "decimal" will combine with rational values to produce decimal values, much like in MATLAB itself.
Note: if you have something like
sym(pi, 'd')
then that is going to be working on the MATLAB binary approximation of pi, not the irrational Pi. Likewise
sym(sqrt(2), 'd') - sqrt(sym(2, 'd'))
will be non-zero if digits exceeds 16, because sqrt(2) would be executed at the MATLAB level, giving a double precision result that would then be converted to symbol, whereas sym(2,'d') is going to convert to symbol and then sqrt() of that would be taking the sqrt() at symbolic level at higher precision.