如何环绕范围 [英] How to wrap around a range

查看:63
本文介绍了如何环绕范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

程序中的角度以0至2pi表示。我想要一种方法来添加两个角度,如果结果高于2pi,则将2pi缠绕为0。或者,如果我从某个角度减去一个角度并且该角度小于0,则它将环绕2pi。

Angles in my program are expressed in 0 to 2pi. I want a way to add two angles and have it wrap around the 2pi to 0 if the result is higher than 2pi. Or if I subtracted an angle from an angle and it was below 0 it would wrap around 2pi.

有没有办法做到这一点?

Is there a way to do this?

谢谢。

推荐答案

您要寻找的是模数。 fmod函数将不起作用,因为它会计算余数而不是算术系数。这样的东西应该可以工作:

What you are looking for is the modulus. The fmod function will not work because it calculates the remainder and not the arithmetic modulus. Something like this should work:

inline double wrapAngle( double angle )
{
    double twoPi = 2.0 * 3.141592865358979;
    return angle - twoPi * floor( angle / twoPi );
}

编辑:

余数通常定义为经过长时间除法后剩余的数(例如18/4的余数为2,因为 18 = 4 * 4 + 2 )。当您有负数时,这变得毛茸茸。查找有符号除法的余数的常见方法是使余数与结果具有相同的符号(例如,-18/4的余数为-2,因为 -18 = -4 * 4 +- 2 )。

The remainder is commonly defined as what is left over after long division (eg. the remainder of 18/4 is 2, because 18 = 4 * 4 + 2). This gets hairy when you have negative numbers. The common way to find the remainder of a signed division is for the remainder to have the same sign as the result (eg. the remainder of -18/4 is -2, because -18 = -4 * 4 + -2).

x模数y的定义是等式x = y * c + m中m的最小正值,给定c为整数。因此 18 mod 4 将为2(其中c = 4),但是 -18 mod 4 也将为2(其中c = -5)。

The definition of x modulus y is the smallest positive value of m in the equation x=y*c+m, given c is an integer. So 18 mod 4 would be 2 (where c=4), however -18 mod 4 would also be 2 (where c=-5).

x mod y 的最简单计算方法是 xy * floor(x / y),其中floor是小于该值的最大整数等于或等于输入。

The simplest calculation of x mod y is x-y*floor(x/y), where floor is the largest integer that is less than or equal to the input.

这篇关于如何环绕范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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