夹角功能

问题描述 投票:0回答:1

我想要一个函数对于任何给定的有限数返回 [0, tau) 范围内的值。

天真地我会写

const TAU = Math.PI * 2;
function clamp(theta) {
    while(theta < 0) theta += TAU;
    return theta % TAU;
}

但是,我注意到,对于正θ,这是恒定时间,对于负θ,这是线性时间。是否有一个对于所有输入值都是 O(1) 的解决方案?

algorithm math
1个回答
0
投票

%
在您的语言中如何用于否定论证?

在 Python 中,它给出 modulo

def clamp(theta):
   return theta % TAU

返回所需的结果(例如,

pi/2, 5*pi/2, -3*pi/2
的结果相同)

如果

%
余数,您可以使用下一个表达式(推荐用于 JS)来消除负结果:

((theta % TAU) + TAU) % TAU
© www.soinside.com 2019 - 2024. All rights reserved.