Reputation: 1587
I am trying to set a variable by vpa
(variable-precision arithmetic). If I try
a=vpa(tanh(1))
then a=0.76159415595576485102924380043987
as desired. Now I try to do it in a loop:
a=[];
for i=1:3
a(i)=vpa(tanh(1));
end
However, now when I output a(1)
, I just get the value 0.761594155955765
. Why don't I get the last digits as I did in the first case?
Upvotes: 2
Views: 285
Reputation: 18494
There are two problems with your code.
First, if you run class(a)
after your for
loop you'll see that a
is a 'double'
rather than a 'sym'
. The reason for this is because you initially allocated a
as an empty double precision array: a = [];
. Each time you insert symbolic variable precision values into this, they are cast to be the same class as a
.
To properly build a symbolic array, you need to allocate as such:
a = sym([]);
for i = 1:3
a(i) = vpa(tanh(1));
end
a
class(a)
Even better, specify the final size:
n = 3;
a = sym(zeros(n,1)); % Or a = zeros(n,1,'sym');
for i = 1:n
a(i) = vpa(tanh(1));
end
a
class(a)
In your case, both of the above options are equivalent to the following because you're applying vpa
as the last operation on each element:
n = 3;
a = zeros(n,1);
for i = 1:n
a(i) = tanh(1);
end
a = vpa(a);
This leads to the second issue, which is that your calculations are not really taking advantage of variable precision. You need to make sure that all values are converted to symbolic or variable precious before performing operations on them. For example:
a = vpa(tanh(1)) % Calculate tanh(1) as double then convert to vpa
b = tanh(vpa(1)) % Calculate tanh(1) using actual variable precision
a-b
returns 0.000000000000000037090214482164921742783153748416
. In other words, vpa(tanh(1))
calculates the hyperbolic tangent in double precision and tanh(vpa(1))
does so using variable precision.
Upvotes: 2