![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/599970/image.png)
Please help with unexpected outputs from symbolic expressions.
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Doheon Lee
am 28 Apr. 2021
Kommentiert: Doheon Lee
am 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)
0 Kommentare
Akzeptierte Antwort
Steven Lord
am 28 Apr. 2021
phi_1 = (1 + sqrt(sym(5)))/5
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/599970/image.png)
phi_2 = (1 + sqrt(5))/sym(5)
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
x2 = sym(2^2000) % overflows to Inf before MATLAB can convert to symbolic
2 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Symbolic Variables, Expressions, Functions, and Preferences finden Sie in Help Center und File Exchange
Produkte
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!