2 views (last 30 days)
Doheon Lee on 28 Apr 2021
Commented: Doheon Lee on 30 Apr 2021
Hi MATLAB Community,
I am strugling with symbolic expressions.
In the following codes, the upper code (phi_1) outputs a symbolic function as expected, while the lower code (phi_2) outputs a strange numbers.
So, when using symbolic function, it seems tthat 'sym' must be applied to a right number in a given function. How can we know which number is the right one to apply 'sym'? In the following example, 'sqrt(sym(5))' is a good one, but not 'sym(5)' in the denominator.
And what does it means the strange numbers come from phi_2?
phi_1 = (1 + sqrt(sym(5)))/5;
phi_2 = (1 + sqrt(5))/sym(5);
Another question is why f(1) in Example 1 outputs a value, while f_sin(1) in Example 2 outputs a formular?
It is very confusing. Thank you very much for the help in advance.
% Example 1
syms f(x)
f(x) = x + 1;
f(1)
% Example 2
syms f_sin(x)
f2(x) = sin(x);
f_sin(1)

Steven Lord on 28 Apr 2021
phi_1 = (1 + sqrt(sym(5)))/5
phi_1 = This performs the sqrt call first on a sym object representing to generate a sym result. The addition and division are performed symbolically because one of the inputs was symbolic.
phi_2 = (1 + sqrt(5))/sym(5)
phi_2 = This performs the computation of 1+sqrt(5) numerically then converts the result into a sym object when MATLAB divides by the sym value 5. Symbolic Math Toolbox cannot recognize that the double value of 1+sqrt(5) is that expression so instead it converts it into a rational number. See the description of the 'r' flag in the documentation for the sym function.
If you're performing a calculation where performing the calculation numerically and converting to a symbolic result after may lose precision (or may overflow / underflow double precision) I'd work with the symbolic versions of some exact constants.
x1 = sym(2)^2000 % Symbolic calculations avoid overflow
x1 =
114813069527425452423283320117768198402231770208869520047764273682576626139237031385665948631650626991844596463898746277344711896086305533142593135616665318539129989145312280000688779148240044871428926990063486244781615463646388363947317026040466353970904996558162398808944629605623311649536164221970332681344168908984458505602379484807914058900934776500429002716706625830522008132236281291761267883317206598995396418127021779858404042159853183251540889433902091920554957783589672039160081957216630582755380425583726015528348786419432054508915275783882625175435528800822842770817965453762184851149029376
x2 = sym(2^2000) % overflows to Inf before MATLAB can convert to symbolic
x2 =
##### 2 CommentsShowHide 1 older comment
Doheon Lee on 30 Apr 2021
I have just found an unepxected result.
x1 = sym(2)^2000
x1 =
inf
But without x1, the result is a long numbers
sym(2)^2000
1606938044258990275541962092341162602522202993782792835301376
Shouldm't the second code (wihtout x1) output the same results to the first code?