MATLAB Answers

Please help with unexpected outputs from symbolic expressions.

조회 수: 1(최근 30일)
Doheon Lee
Doheon Lee 2021년 4월 28일
댓글: Doheon Lee 2021년 4월 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;
% Example 2
syms f_sin(x)
f2(x) = sin(x);

채택된 답변

Steven Lord
Steven Lord 2021년 4월 28일
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 = 
x2 = sym(2^2000) % overflows to Inf before MATLAB can convert to symbolic
x2 = 
  댓글 수: 2
Doheon Lee
Doheon Lee 2021년 4월 30일
I have just found an unepxected result.
x1 = sym(2)^2000
x1 =
But without x1, the result is a long numbers
Shouldm't the second code (wihtout x1) output the same results to the first code?

댓글을 달려면 로그인하십시오.

추가 답변(0개)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by