1

I currently have the following code:

count = 20;

n = zeros(count, 1);
P = zeros(count, 1);

for i = 1:count
    n(i) = i;
    P(i) = sym(i)^i + (sym(1-i))^(i-1);
    if i == (count)
        T = table(n,P)
    end
end

This gives me a table with a set of values. However, some of the values are losing precision because they have too many digits. I am aware that MATLAB allows for up to 536870913 digits of precision. How do I make my table values not lose precision? Note: if I were to just do the following operation (for example): sym(200)^2010, I would get the full precision value, which has 4626 digits. Doing this for table values doesn't seem to work, though, for some strange reason. If someone could please help me with this I would be extremely grateful as I have been struggling with this for several hours now.

  • Looking at your code, I think you already lose the precision at the `P(i) = sym(i)^i + (sym(1-i))^(i-1);` step. P is of type double, so once you insert your symbolic expression it is probably double? To get an array of sym use `P=sym('x',[1,count]) `. – Daniel Dec 11 '19 at 06:34

1 Answers1

3

As @Daniel commented, the problem is that you are casting to double when storing it in P. MATLAB only has the precision you mention when using symbolic variables, but when you get into the numerical world, you can only store a finite amount of precision.

To be exact, once you define P as a double (zeros returns a double vector), the biggest integer you can store such that all of its smaller integers are precise is 2^53, way smaller than your P(20). This means that any integer bigger than 2^53 is not ensured to be precise on a double valued vector.

Your solution is thus to avoid casting, to store the variable on a sym type P. Note that the above also applies to later maths. If you plan to use this variable in some equation, remember that when you pass it to numerical form, you will lose precision. Often this does not matter, as the precision lost is very small, but you should know it.

If you want to learn more about how numerical precision work on computers, I suggest reading the following Q&A: Why is 24.0000 not equal to 24.0000 in MATLAB?

Sym solution:

count = 20;

n = zeros(count, 1);
P = sym('integer',[count, 1]);

for i = 1:count
    n(i) = i;
    P(i) = sym(i)^i + (sym(1-i))^(i-1);
    if i == (count)
        T = table(n,P)
    end
end

returns

>> T.P(20)

ans =

102879180344339686410876021
Ander Biguri
  • 35,140
  • 11
  • 74
  • 120