matlab - setting variables with vpa in loops -
i trying set variable vpa
(variable-precision arithmetic). if try
a=vpa(tanh(1))
then a=0.76159415595576485102924380043987
desired. try in loop:
a=[]; i=1:3 a(i)=vpa(tanh(1)); end
however, when output a(1)
, value 0.761594155955765
. why don't last digits did in first case?
there 2 problems code.
first, if run class(a)
after for
loop you'll see a
'double'
rather 'sym'
. reason because allocated a
empty double precision array: a = [];
. each time insert symbolic variable precision values this, cast same class a
.
to build symbolic array, need allocate such:
a = sym([]); = 1:3 a(i) = vpa(tanh(1)); end class(a)
even better, specify final size:
n = 3; = sym(zeros(n,1)); % or = zeros(n,1,'sym'); = 1:n a(i) = vpa(tanh(1)); end class(a)
in case, both of above options equivalent following because you're applying vpa
last operation on each element:
n = 3; = zeros(n,1); = 1:n a(i) = tanh(1); end = vpa(a);
leads second issue, calculations not taking advantage of variable precision. need make sure values converted symbolic or variable precious before performing operations on them. example:
a = vpa(tanh(1)) % calculate tanh(1) double convert vpa b = tanh(vpa(1)) % calculate tanh(1) using actual variable precision a-b
returns 0.000000000000000037090214482164921742783153748416
. in other words, vpa(tanh(1))
calculates hyperbolic tangent in double precision , tanh(vpa(1))
using variable precision.
Comments
Post a Comment