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!