在 bash 中四舍五入到最接近的 2 的幂

Wes*_*des 2 math bash shell scripting arithmetic-expressions

我正在编写 shell 脚本,我想将给定的整数四舍五入到最接近的 2 的幂。我们可以使用 Linux 命令行中提供的任何标准工具。你可以假设 bash。因此算术扩展和 bc 都可以使用。

在对数刻度上舍入到最接近的 2 的幂(不是作为 shell 脚本):

r = 2^(round(log2(x)));
Run Code Online (Sandbox Code Playgroud)

想象一下函数的输入和输出如下:

# power2 11
8
# power2 12
16
# power2 13
16
# power2 16
16
Run Code Online (Sandbox Code Playgroud)

我不确定我们是否可以从 bash shell 脚本获取日志。我们有圆吗?没有把握。

但我知道你非常聪明,可以想出一个优雅且令人印象深刻的解决方案。

Joh*_*024 5

使用这个函数:

power2() { echo "x=l($1)/l(2); scale=0; 2^((x+0.5)/1)" | bc -l; }
Run Code Online (Sandbox Code Playgroud)

例子

$ power2 11
8
$ power2 12
16
$ power2 13
16
$ power2 16
16
$ power2 63
64
Run Code Online (Sandbox Code Playgroud)

怎么运行的

该echo语句创建一个将解释为命令的字符串bc。命令由以下部分组成:

  • x=l($1)/l(2)

    这设置x为第一个参数 的自然对数的值,l($1)除以 2 的自然对数,l(2)。

  • scale=0

    通过设置scale为 0,以后的除法将截断为整数。

  • 2^((x+0.5)/1)

    表达式(x+0.5)/1四舍五入x到最接近的整数。然后我们将其结果求 2 次方。