舍入到给定碱的最接近的整数幂 [英] Rounding to the nearest integer power of a given base

查看:138
本文介绍了舍入到给定碱的最接近的整数幂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想圆一个数字的其他号码,下一个最小功率。我并不特别是其四舍五入哪个方向,但我preFER向下如果可能的话。

I'm trying to round a number to the next smallest power of another number. I'm not particular on which direction it rounds, but I prefer downwards if possible.

X 是我四舍五入将满足: X> 0 ,通常的范围内符合 0℃ X - LT; = 1 。只有很少会是大于1。

The number x that I'm rounding will satisfy: x > 0, and usually fits within the range 0 < x <= 1. Only rarely will it be above 1.

更一般地,我的问题是:给定一个数 X ,我怎么能圆到一些基本的最接近的整数次幂 b

More generally, my problem is: Given a number x, how can I round it to the nearest integer power of some base b?

我希望能够圆对任意的基础,但那些我最关心的是,此刻的基地2和2如2 ^(1/2),2 ^分数幂(1/4 ),等等。这是我目前的算法基地2个。

I would like to be able to round towards arbitrary bases, but the ones I'm most concerned with at the moment is base 2 and fractional powers of 2 like 2^(1/2), 2^(1/4), and so forth. Here's my current algorithm for base 2.

double roundBaseTwo(double x)
{
    return 1.0 / (1 << (int)((log(x) * invlog2))
}

任何帮助将是AP preciated!

Any help would be appreciated!

推荐答案

您已经得到了正确的想法;任何基础X, X ^楼(log_x(N))是你想要的。 (这里的 log_x 重presents日志到基本的 X 的')
在C#:<​​/ P>

You've got the right idea; for any base x, x ^ floor( log_x(n) ) is what you want. (Where log_x represents 'log to the base x')
In C#:

static double roundBaseX(double num, double x)
{
    return Math.Pow(x, Math.Floor(Math.Log(num, x)));
}

如果你不能把对数为任意的基础,只要用公式: log_x(N)=的log(n)/日志(X)

If you can't take logarithms to an arbitrary base, just use the formula: log_x(n) = log(n) / log(x)

这篇关于舍入到给定碱的最接近的整数幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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