wil*_*lc2 5 math angle gesture-recognition fuzzy-comparison
我正在编写 iPhone 代码,模糊地识别滑动的线是否是直线。我获取两个端点的方位角,并将其与 0、90、180 和 270 度进行比较,公差为正负 10 度。现在我用一堆 if 块来做这件事,这看起来超级笨重。
\n\n如何编写一个函数,在给定方位角0..360、公差百分比(例如 20% = (-10\xc2\xb0 到 +10\xc2\xb0))和直角(如90 度)的情况下,返回是否轴承是否在公差范围内?
\n\n更新: 也许我太具体了。我认为一个很好的通用函数可以确定一个数字是否在另一个数字的百分比范围内,在许多领域都有用处。
\n\n例如:swipeLength数字是否在maxSwipe的10%以内?那会有用的。
\n\n BOOL isNumberWithinPercentOfNumber(float firstN, float percent, float secondN) {\n // dunno how to calculate\n }\n\n BOOL result;\n\n float swipeLength1 = 303; \n float swipeLength2 = 310; \n\n float tolerance = 10.0; // from -5% to 5%\n float maxSwipe = 320.0;\n\n result = isNumberWithinPercentOfNumber(swipeLength1, tolerance, maxSwipe); \n // result = NO\n\n result = isNumberWithinPercentOfNumber(swipeLength2, tolerance, maxSwipe);\n // result = YES\nRun Code Online (Sandbox Code Playgroud)\n\n你明白我的意思吗?
\n20% 小数化等于 0.2。只需除以 100.0 即可得到小数。除以 2.0 即可得到可接受范围的一半。(合并为200.0除数)
在此基础上,加上 1.0 并减去 1.0,即可得到 90% 和 110% 值。如果第一个数字在范围之间,那么就可以了。
BOOL isNumberWithinPercentOfNumber(float firstN, float percent, float secondN) {
float decimalPercent = percent / 200.0;
float highRange = secondN * (1.0 + decimalPercent);
float lowRange = secondN * (1.0 - decimalPercent);
return lowRange <= firstN && firstN <= highRange;
}
Run Code Online (Sandbox Code Playgroud)
注意:这里没有对 NaN 或负值进行错误检查。您需要将其添加到生产代码中。
更新:使百分比包含+/-范围。