How to reverse fixed point binary log algorithm for fractional power of 2?

陌路散爱 提交于 2020-04-30 06:28:19

问题


I found a fast binary logarithm algorithm for fixed points in an answer to this question: Fast fixed point pow, log, exp and sqrt, based on an algorithm by Clay S. Turner. Is it possible to "reverse" this to calculate fractional powers of two? e.g:

// log2(3) = 1.5849609375
log2fix(196608, 16) == 103872
pow2fix(103872, 16) == 196608

Here's the code from Dan Moulding:

#include <errno.h>
#include <stddef.h>

#include "log2fix.h"

int32_t log2fix (uint32_t x, size_t precision)
{
    int32_t b = 1U << (precision - 1);
    int32_t y = 0;

    if (precision < 1 || precision > 31) {
        errno = EINVAL;
        return INT32_MAX; // indicates an error
    }

    if (x == 0) {
        return INT32_MIN; // represents negative infinity
    }

    while (x < 1U << precision) {
        x <<= 1;
        y -= 1U << precision;
    }

    while (x >= 2U << precision) {
        x >>= 1;
        y += 1U << precision;
    }

    uint64_t z = x;

    for (size_t i = 0; i < precision; i++) {
        z = z * z >> precision;
        if (z >= 2U << (uint64_t)precision) {
            z >>= 1;
            y += b;
        }
        b >>= 1;
    }

    return y;
}

来源:https://stackoverflow.com/questions/61471447/how-to-reverse-fixed-point-binary-log-algorithm-for-fractional-power-of-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!