MATLAB: Output: Long numbers for no reason

formatlong numbers

Hi,
it's me with another question – sorry! 😉 I have encountered this problem for a while now and it's more and more annoying so I decided to ask here: Often, Matlab doesn't calculate stuff "until the end". For example: I get the info that the solution for a random task is:
ans=-(1152921504606846976*sin(7821430514075775/72057594037927936) - 368769787030653356*cos(7821430514075775/72057594037927936) + 46928583084454650*cos(54750013598530425/72057594037927936) + (23464291542227325*sin(54750013598530425/72057594037927936))/2 + 288230376151711744*cos(23464291542227325/36028797018963968) - 1152921504606846976*sin(23464291542227325/36028797018963968) - 241301793067257094*cos(39107152570378875/72057594037927936) + (2329307300755921277*sin(39107152570378875/72057594037927936))/2 + 274912620861744056)/(50*(576460752303423488*cos(7821430514075775/72057594037927936) + 23464291542227325*sin(7821430514075775/72057594037927936) - 576460752303423488))
This, of course, doesn't help me much. I have to copy and paste the whole expression into the command window again and end up getting the final value of approx. 0.012521. I guessed that it has something to do with the numeric format but various tries haven't changed anything, it's the same in every format. Of course I used Google but that didn't lead to anything in this case. So I hope someone here might have an answer for me?

Best Answer

When you perform computations using sym objects, MATLAB will not approximate the result of those computations as a double precision result normally. In order to approximate the results you need to either do something that requires the results to be double precision (like assigning the variable into an element of a double array) or explicitly tell MATLAB to approximate it using the double or vpa functions.
two = sym(2);
sqrt2 = sqrt(two) % displayed symbolically
x = 0;
x(1) = sqrt2
s2 = double(sqrt2)
s2_2 = vpa(sqrt2)
Note that sqrt2 is displayed as 2^(1/2) but x, s2, and s2_2 all display that quantity to a certain number of decimal places. The format function will not affect the display of sqrt2 or s2_2 but will affect the display of x or s2.