-2

I write this code i Swifts Playground, but the result is wrong:

import UIKit

var degree:Double = 60
var result = cos(degree)

-- The result shall be 0.5 but Playground get me the answer = -0.9524129804151563.

If I choose 30 degrees the result will be = 0.154251449887584

What is wrong??

Dániel Nagy
  • 11,815
  • 9
  • 50
  • 58
  • I would downvote if I could. Should have checked degrees and radians first. – Link Aug 01 '15 at 16:25
  • Just lookup `cos` in the Xcode documentation viewer, and you'll find *"The cos() function computes the cosine of x (measured in radians)."*. – Martin R Aug 01 '15 at 16:27

1 Answers1

3

Trigonometric functions that take angles treat values as if they are expressed in radians, not degrees. When you pass 60, you get back cosine of 60 radians, not 60 degrees. To convert degrees to radians, multiply the value by π, and divide by 180.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Thank you very much. You have save my day. – Chris Hunter Aug 02 '15 at 09:33
  • @ChrisHunter You are welcome. If this answers your question, consider accepting the answer by clicking the check mark next to it. This would let other site visitors know that you are no longer actively looking for an improved answer, and earn you a badge on Stack Overflow. – Sergey Kalinichenko Aug 02 '15 at 10:30