Please help with unexpected outputs from symbolic expressions.
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Steven Lord
2021-4-28
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.
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
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Calculus 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!