我为什么要模数减法?

时间:2012-01-26 15:09:01

标签: language-agnostic

天哪,这一定很简单。我有一个范围(0,2π)的标题和两个点,我从中得到标题。我必须比较它们,看看是否在另一个范围内。到目前为止我得到的是。

//get the angle
float angle = atan(here.x - there.x, here.y - there.y);

//atan2 uses (-pi, pi) range, convert to (0, 2pi)
if(angle < 0) angle += 2*pi;

//subtract them pesky headings
float diff = angle - givenAngle;

//a difference of 350 degrees really is a difference of 10 degrees
if(diff > pi) diff = 2*pi - diff;

//a difference of -10 degrees really is a difference of 10 degrees
if(diff < 0) diff *= -1;

//check if the point is in range of givenAngle
if(diff > fov) do_magic(diff - fov);

但是,当两个角度都变为零时,我会遇到各种各样的问题,而且我在解决这个问题时浪费了太多的脑力。

我在哪里做错了?如何正确找到两个标题之间的差异?

2 个答案:

答案 0 :(得分:2)

我怀疑您的操作顺序可能略有错误:

//a difference of 350 degrees really is a difference of 10 degrees
if(diff > pi) diff = 2*pi - diff;

//a difference of -10 degrees really is a difference of 10 degrees
if(diff < 0) diff *= -1;

这不会导致-350的差异,但是如果你切换它的语句:

//a difference of -10 degrees really is a difference of 10 degrees
if(diff < 0) diff *= -1;

//a difference of ±350 degrees really is a difference of 10 degrees
if(diff > pi) diff = 2*pi - diff;

答案 1 :(得分:0)

其中一个主要问题是:

float angle = atan(here.x - there.x, here.y - there.y);

注意到这一点有点棘手,但这不是atan的正确参数顺序 - 偶数the mathematical definition on wikipedia在之前采用y组件(正弦) x组件(余弦)。

float angle = atan(here.y - there.y, here.x - there.x);

第二个问题是,事实证明,angle关闭了180度。换句话说,我应该计算here - there

,而不是计算there - here
float angle = atan(there.y - here.y, there.x - here.x);

sverre's observation中添加有关错误操作顺序的内容,我们的内容会更好:

float angle = atan(there.y - here.y, there.x - here.x);
if(angle < 0) angle += pi * 2; //use (0, 2pi) range, the same as angle
float diff = abs(angle - givenAngle);
if(diff > pi) diff = 2*pi - diff;
if(diff > fov) do_magic(diff - fov);