如果我有一个整数n,并且我想知道最高位的位置(也就是说,如果最低有效位在右边,我想知道最左边位的位置是1),找出最快捷/最有效的方法是什么?
我知道POSIX支持ffs()strings.h中的一个方法来查找第一个设置位,但似乎没有相应的fls()方法.
是否有一些非常明显的方法可以解决这个问题?
如果你不能使用POSIX功能来实现可移植性呢?
编辑:如何在32位和64位架构上运行的解决方案(许多代码清单似乎只能在32位整数上运行).
假设您必须计算域在0.01到360.01之间的正弦(余弦或正切 - 无论如何).(使用C#)
什么会更高效?
我会反驳说,鉴于域名,选项2会快得多.在域精度(0.0000n)的什么时刻,计算的性能超过了查找.
我尝试遵循“自然对数 (ln) 和指数的有效实现”主题,以便能够在没有 math.h 的情况下实现对数函数。所描述的算法对于 1 到 2 之间的值(标准化值)效果很好。但是,如果这些值未标准化并且我遵循标准化说明,那么我会得到错误的值。
链接:点击这里
如果我按照示例整数值 12510 执行代码,我会得到以下结果:
y = 12510 (0x30DE),log2 = 13,除数 = 26,x = 481,1538
float ln(float y) {
int log2;
float divisor, x, result;
log2 = msb((int)y); // See: /sf/answers/347960161/
divisor = (float)(1 << log2);
x = y / divisor; // normalized value between [1.0, 2.0]
result = -1.7417939 + (2.8212026 + (-1.4699568 + (0.44717955 - 0.056570851 * x) * x) * x) * x;
result += ((float)log2) * 0.69314718; …Run Code Online (Sandbox Code Playgroud) After reading this question, I'm wondering what happens under the hood when np.exp is called: what is the mathematical/numerical routine used to derive the values in the returned array? For example, I think that to compute np.sqrt(x), a solution in y to y ** 2 - x = 0 is found using Newton's method.
(np.exp 的文档字符串没有说明这是如何完成的)