如何计算一个浮点数的另一个浮点数的幂?
我试图弄清楚如何在 bash 中计算涉及括号和指数的数学表达式。请随意提供使用 sed、awk、perl、bash 的解决方案,
例如
i=0.0545
j=360
(1+ $i * 2.43 / 100.0) ^ ($j/940) -1
您将如何在 bash 中编码并获得浮点结果?
I am trying to figure out how compute a math expression involving parenthesis and exponents in bash. Feel free to offer solutions using sed, awk, perl, bash
for example
i=0.0545
j=360
(1+ $i * 2.43 / 100.0) ^ ($j/940) -1
How would you encoded in bash and get the floating point result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
要计算x^n,请使用:
bc -l <<< "e($n*l($x))"
或
echo "e($n*l($x))" | bc -l
理论
bc
命令不处理使用浮点指数的求幂。但是,它具有指数e()
和对数l()
函数。使用这两个函数,我们可以通过属性 x^n = exp(log(x^n)) = exp(n*log(x)) 来计算幂。To calculate x^n use:
bc -l <<< "e($n*l($x))"
or
echo "e($n*l($x))" | bc -l
Theory
The
bc
command doesn't deal with exponentiation using float exponents. However, it has the exponenciale()
and the logarithmicl()
functions. Using these two functions, we can calculate the exponentiation by the property x^n = exp(log(x^n)) = exp(n*log(x)).这是用 perl 写的:
Here it is in perl:
当我需要精度时,我使用 bc 进行数学计算(但在这种情况下不起作用,因为它不支持小数指数):
最简单的是使用 awk:
如果你不太懂 awk,你可能需要:
I use
bc
for math when I need precision (but doesn't work in this case as it doesn't support fractional exponent):Easiest is to go with
awk
:If you donno awk so much, you might need:
(您可能需要编辑您的帖子以包含您期望的表达式的正确答案;-)
使用 awk。它需要一条线索表明您需要浮点计算,因此更改任何整数表达式部分以包含尾随
.0
(如下所示)。更好的是,将 BEGIN 更改为 END 并使用 awk cmd-line var 赋值,即
(我想我最近读到 BEGIN 不会处理 cmd 行上的赋值,但它确实可以与 END 一起使用(显然))。
我希望这有帮助。
(You might want to edit your post to include what you expect as the correct answer for your expression ;-)
Use awk. It needs a clue that you are expecting floating point calcs, so change any whole number expression parts to include a trailing
.0
(as below).Better yet, change BEGIN to END and use awk cmd-line var assignment, i.e.
(I think I've read recently that BEGIN won't process assignments on the cmd line, but it does work with END (obviously)).
I hope this helps.