How to fix the large and mad fractions when dealing with symbolic vars

172 ビュー (過去 30 日間)
Hi guys,
I face this often, as you can see below that cos(phi) and cos(psi) are decent entities, but when they are used with a symbolic variable (kn here), it shows huge fractions. Is there an easy way to make the coefficients of k1 k2 and k3 in the short format or some decent fractions.
Even something as trivial as k1*cos(pi/2) is not evaluated to be 0 as shown below. I fear that this leads to truncation errors.
Thanks in advance.
cos(pi/2)
ans = 6.1232e-17
syms a
a*cos(pi/2)
ans = 
  4 件のコメント
Torsten
Torsten 2022 年 9 月 18 日
I could only see your screenshots after I opened your contribution using "Edit".
Mohd Aaquib Khan
Mohd Aaquib Khan 2022 年 9 月 18 日
I fixed it now, this below is what I meant
cos(pi/2)
ans = 6.1232e-17
syms a
a*cos(pi/2)
ans = 

サインインしてコメントする。

採用された回答

Walter Roberson
Walter Roberson 2022 年 9 月 19 日
The answer you are looking for is
digits(4)
sympref('FloatingPointOutput',true);
However, I do not recommend this.
  1 件のコメント
Mohd Aaquib Khan
Mohd Aaquib Khan 2022 年 9 月 19 日
Yes thank you, vpa() also works fine for the same result.
phi = [50, 25, 30 90]';
syms a
vpa(cosd(phi)*a,4)
ans = 
digits(4)
sympref('FloatingPointOutput',true);
phi = [50, 25, 30 90]';
cosd(phi)*a
ans = 

サインインしてコメントする。

その他の回答 (2 件)

Steven Lord
Steven Lord 2022 年 9 月 18 日
Symbolically, use vpa or double or use the sympref function to change the FloatingPointOutput preference.
Numerically, if you want to compute the sine or cosine of an angle expressed as a multiple of pi, use sinpi or cospi respectively.
format longg
[sin(0.5*pi), cos(0.5*pi); sinpi(0.5), cospi(0.5)]
ans = 2×2
1 6.12323399573677e-17 1 0
  1 件のコメント
Mohd Aaquib Khan
Mohd Aaquib Khan 2022 年 9 月 19 日
Thank you, yes vpa and sympref are both working fine and that is what I wanted.

サインインしてコメントする。


Paul
Paul 2022 年 9 月 18 日
In this expression
syms a
a * cos(pi/2)
ans = 
the cos() is evaluated numerically and the result converted to a sym to multiply with a. The numerical cos(pi/2) is not zero.
Force the cos to be evaluated symbolically
a * cos(pi/sym(2))
ans = 
0
or
a * cos(sym(pi)/2)
ans = 
0
  3 件のコメント
Torsten
Torsten 2022 年 9 月 19 日
For phi = 30 and phi = 90, cos(phi) is correctly simplified.
What would you expect for cos(50) and cos(25) ? I don't see a simple representation.
Walter Roberson
Walter Roberson 2022 年 9 月 19 日
You should never eval() a symbolic expression. eval() of a symbolic expression is not documented by Mathworks. In practice it is treated as eval(char()) of the expression. However, char() of a symbolic expression is written in a mix of MATLAB, English, and the internal MuPAD programming language, and is not generally something that can be computed.

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeNumber Theory についてさらに検索

製品


リリース

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by