脚本和浮点除法 [英] Division in script and floating-point

查看:20
本文介绍了脚本和浮点除法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的脚本中执行以下操作:

I would like to do the following operation in my script:

1 - ((m - 20) / 34)

我想将此操作的结果分配给另一个变量.我希望我的脚本使用浮点数学.例如,对于 m = 34:

I would like to assign the result of this operation to another variable. I want my script use floating point math. For example, for m = 34:

results = 1 - ((34 - 20) / 34) == 0.588

推荐答案

您可以使用 bc 计算器.如果您将 increease scale 从其默认值 0 设置为 0,它将使用小数(不是二进制浮点)进行任意精度的数学运算:

You could use the bc calculator. It will do arbitrary precision math using decimals (not binary floating point) if you set increease scale from its default of 0:

$ m=34
$ bc <<< "scale = 10; 1 - (($m - 20) / 34)"
.5882352942

-l 选项将加载标准数学库并将比例默认为 20:

The -l option will load the standard math library and default the scale to 20:

$ bc -l <<< "1 - (($m - 20) / 34)"
.58823529411764705883

然后您可以使用 printf 来格式化输出,如果您愿意的话:

You can then use printf to format the output, if you so choose:

printf "%.3f
" "$(bc -l ...)"

这篇关于脚本和浮点除法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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