I'm not sure what is wrong with this code regarding the sin and cos function.

Hello, I have a problem with the following code:
angle=input('what is the angle in degrees: ');
t=angle*(pi/180);
if cos(t)<10^(-20)
disp('error! cos is close to zero');
else
y=sin(t)/cos(t);
fprintf('tan is equal to %f',y);
end
My professor said that sin and cos work in radians so I converted the degrees to radians. However, whenever I test for something like 90 degrees (when cos is 0), it should be displaying the error message, but it's not.
I get the following
what is the angle in degrees: 90
tan is equal to 16331239353195370.000000>>

 採用された回答

Youssef  Khmou
Youssef Khmou 2014 年 4 月 6 日
Like Azzi said, pi contains infinite decimal numbers, To avoid this ambiguity i recommend you to use the degree functions instead of radians cosd and sind,
cosd(90)=0
cos(pi/2)=6.1232e-017

2 件のコメント

liv
liv 2014 年 4 月 6 日
This fixed it. Thank you so much.
Youssef  Khmou
Youssef Khmou 2014 年 4 月 6 日
if the problem is solved, accept the answer.

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

その他の回答 (1 件)

Azzi Abdelmalek
Azzi Abdelmalek 2014 年 4 月 6 日

1 投票

You can check the value of cos(90*pi/180) and compare it with 10^(-20)

5 件のコメント

liv
liv 2014 年 4 月 6 日
I just tried that and it says the value is false.
cos(90*pi/180)<10^-20
ans =
0
>> cos(pi/2)
ans =
6.1232e-17
but cos(pi/2) is zero. Would you know why MatLab is not displaying it as zero?=/ And thank you for your earlier response; it helped me see where the problem is.
Type
pi
is it an exact pi?
liv
liv 2014 年 4 月 6 日
it gives
pi
ans =
3.1416
Azzi Abdelmalek
Azzi Abdelmalek 2014 年 4 月 6 日
編集済み: Azzi Abdelmalek 2014 年 4 月 6 日
OK, you know that the exact pi contains much more decimals. what Matlab or any other langage di is an approximation of pi
liv
liv 2014 年 4 月 6 日
Thank you very much!

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

カテゴリ

ヘルプ センター および File ExchangeMATLAB についてさらに検索

質問済み:

liv
2014 年 4 月 6 日

編集済み:

2014 年 4 月 6 日

Community Treasure Hunt

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

Start Hunting!

Translated by