问题
I'm beginner developer for iOS. I use some online tutorials to learn Swift and now I'm trying to develop my own calculator. There is task to down "sin" and "cos" buttons by my own, which would return sine or cosine function for entered value.
Of course, there is sin() and cos() functions in the Swift, but I've found, that it returns values in radians, not degrees. I did search and found code, smth like that
func sind(degrees: Double) -> Double {
return sin(degrees * M_PI / 180.0)
}
which I implemented in my code. Now everything looks fine, buttons returns correct values. But there is sine of 180 degrees is 0 and when I enter 180 in my calculator and press "sin" button it returns another value. Same for cosine of 90 degrees, should be 0 but returns another value.
Could you please explain how possible to fix it? Full code at github: https://github.com/senator14/firstcalculator.git
回答1:
The problem with sine and cosine functions is that M_PI is an irrational number is approximately defined as 3.14159265358979323846264338327950288
which means that it has some error.
One possible solutions to your problem is having the ranges of input form -PI/2 to PI/2. This reduces the error of approximation. The following changes your range to -90 to 90 degrees.
sin(((fmod($0, 360) > 270 ? fmod($0, 360) - 270 : ((fmod($0, 360) > 90) ? 180 - fmod($0, 360) : fmod($0, 360))) * M_PI / 180.00)) }
Reference from here
来源:https://stackoverflow.com/questions/32046853/trigonometric-functions-in-swift