Swift 中的三角函数 [英] Trigonometric functions in Swift

查看:81
本文介绍了Swift 中的三角函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 iOS 的初级开发人员.我使用一些在线教程来学习 Swift,现在我正在尝试开发自己的计算器.有消除罪"的任务和cos"我自己的按钮,它将为输入的值返回正弦或余弦函数.

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.

当然,Swift 中有 sin() 和 cos() 函数,但我发现它以弧度而不是度数返回值.我确实搜索并找到了代码,就像那样

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)
}

我在我的代码中实现的.现在一切看起来都很好,按钮返回正确的值.但是 180 度的正弦是 0,当我在计算器中输入 180 并按sin"时,按钮它返回另一个值.与 90 度余弦相同,应为 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.

能否请您解释一下如何修复它?github上的完整代码:https://github.com/senator14/firstcalculator.git>

Could you please explain how possible to fix it? Full code at github: https://github.com/senator14/firstcalculator.git

推荐答案

正弦和余弦函数的问题是 M_PI 是一个无理数近似定义为 3.14159265358979323846264338327950288 这意味着它有一些错误.

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.

您的问题的一种可能解决方案是使用输入形式 -PI/2 到 PI/2 的范围.这减少了近似误差.以下将您的范围更改为 -90 到 90 度.

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)) }

参考来自此处

这篇关于Swift 中的三角函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆