最优雅的unix shell一线式求和列表的任意精度是多少? [英] Most elegant unix shell one-liner to sum list of numbers of arbitrary precision?

查看:85
本文介绍了最优雅的unix shell一线式求和列表的任意精度是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于整数加一线,存在几种建议的shell脚本解决方案;
但是,仔细查看所选的每种解决方案,都有其固有的局限性:

As regards integer adding one-liners, several proposed shell scripting solutions exist;
however, on closer look at each of the solutions chosen, there are inherent limitations:

  • awk会以任意精度和整数大小阻塞(毕竟,它的行为类似于C)
  • bc会对任意长的输入不满意:(sed 's/$/+\\/g';echo 0)|bc
  • awk ones would choke at arbitrary precision and integer size (it behaves C-like, afterall)
  • bc ones would rather be unhappy with arbitrarily long inputs: (sed 's/$/+\\/g';echo 0)|bc

了解跨平台(见[1] [2])最重要的是可移植性问题, 是否有通用的解决方案在实用性简洁性上都是赢家?

Understanding that there may be issues of portability on top of that across platforms (see [1] [2]) which is undesired, is there a generic solution which is a winner on both practicality and brevity?

提示:SunOS& MacOSX是可移植性存在问题的示例.
fi. dc命令可以允许处理任意大的2 ^ n(整数或其他)输入吗?

Hint: SunOS & MacOSX are examples where portability would be an issue.
fi. could dc command permit to handle arbitrarily large 2^n, integer or otherwise, inputs?

[1] awk: https://stackoverflow.com/a/450821/1574494 https://stackoverflow.com/a/25245025/1574494 [2] bc:推荐答案

对于dc(1)的最佳解决方案是在读取输入时对其求和:

An optimal solution for dc(1) sums the inputs as they are read:

$ jot 1000000 | sed '2,$s/$/+/;$s/$/p/' | dc
500000500000

这篇关于最优雅的unix shell一线式求和列表的任意精度是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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