# Shellmath
Introducing decimal arithmetic libraries for the Bash shell, because
they said it couldn't be done... and because:
.
![image info](./image.png)
## Quick-start guide
Download this project and source the file `shellmath.sh` into your shell script,
then fire away at the shellmath API!
The ___basic___ API looks like this:
```
_shellmath_add arg1 arg2 [...] argN
_shellmath_subtract arg1 arg2 # means arg1 - arg2
_shellmath_multiply arg1 arg2 [...] argN
_shellmath_divide arg1 arg2 # means arg1 / arg2
```
The ___extended___ API introduces one more function:
```
_shellmath_getReturnValue arg
```
This function optimizes away the need for ___$(___ subshelling ___)___ in order to capture `shellmath`'s output.
To use this feature, just be sure to set `__shellmath_isOptimized=1` at the top
of your script. (You can find an example in `faster_e_demo.sh`.)
Operands to the _shellmath_ functions can be integers or decimal
numbers presented in either standard or scientific notation:
```
_shellmath_add 1.009 4.223e-2
_shellmath_getReturnValue sum
echo "The sum is $sum"
```
Addition and multiplication are of arbitrary arity; try this on for size:
```
_shellmath_multiply 1 2 3 4 5 6
_shellmath_getReturnValue sixFactorial
echo "6 factorial is $sixFactorial"
```
Subtraction and division, OTOH, are exclusively binary operations.
## The demos
For a gentle introduction to `shellmath` run the demo `slower_e_demo.sh`
with a small whole-number argument, say 15:
```
$ slower_e_demo.sh 15
e = 2.7182818284589936
```
This script uses a few `shellmath` API calls to calculate *e*, the mathematical
constant also known as [Euler's number](https://oeis.org/A001113). The argument
*15* tells the script to evaluate the *15th-degree* Maclaurin polynomial for *e*.
(That's the Taylor polynomial centered at 0.) Take a look inside the script to
see how it uses the `shellmath` APIs.
There is another demo script very much like this one but *different*, and the
sensitive user can *feel* the difference. Try the following, but don't blink
or you'll miss it ;)
```
$ faster_e_demo.sh 15
e = 2.7182818284589936
```
Did you feel the difference? Try the `-t` option with both scripts; this will produce
timing statistics. Here are my results
when running from my minGW64 command prompt on Windows 10 with an Intel i3 Core CPU:
```
$ for n in {1..5}; do faster_e_demo.sh -t 15 2>&1; done | awk '/^real/ {print $2}'
0m0.055s
0m0.051s
0m0.056s
0m0.054s
0m0.054s
$ for n in {1..5}; do slower_e_demo.sh -t 15 2>&1; done | awk '/^real/ {print $2}'
0m0.498s
0m0.594s
0m0.536s
0m0.511s
0m0.580s
```
(When sizing up these timings, do keep in mind that ___we are timing the
calculation of e from its Maclaurin polynomial. Every invocation of either
script is exercising the shellmath arithmetic subroutines 31 times.___)
The comment header in `faster_e_demo.sh` explains the optimization and shows
how to put this faster version to work for you.
## Runtime efficiency competitive with awk and bc
The file `timingData.txt` captures the results of some timing experiments that compare
`shellmath` against the GNU versions of the calculators `awk` and `bc`. The experiments
exercised each of the arithmetic operations and captured the results in a shell variable.
The result summary below shows that `shellmath` is competitive with `awk` and runs faster
than `bc` in these experiments. (One commenter noted that the differences in execution speed
can be partially explained by the fact that `shellmath` and `awk` use finite precision
whereas `bc` uses arbitrary precision. Another factor in these measurements is the need to
subshell 'awk' and 'bc' to capture their results, whereas 'shellmath' writes directly to
the shell's global memory.)
Here are the run times of `shellmath` as a percentage of the `awk` and `bc` equivalents:
```
versus awk versus bc
Addition: 82.2% 40.6%
Subtraction: 95.9% 50.5%
Multiplication: 135.9% 73.3%
Division: 80.3% 43.2%
```
Astute observers will note the experiments provide approximations to the sum, difference,
product, and quotient of *pi* and *e*. Unfortunately I did not gain insight as to which
of these values, if any, are
[transcendental](https://en.wikipedia.org/wiki/Transcendental_number#Possible_transcendental_numbers).
You can find a deeper discussion of shellmath's runtime efficiency
[here](https://github.com/clarity20/shellmath/wiki/Shellmath-and-runtime-efficiency).
## Background
The Bash shell does not have built-in operators for decimal arithmetic, making it
something of an oddity among well-known, widely-used programming languages. For the most part,
practitioners in need of powerful computational building blocks have naturally opted
for *other* languages and tools. Their widespread availability has diverted attention
from the possibility of *implementing* decimal arithmetic in Bash and it's easy to assume
that this ***cannot*** be done:
+ From the indispensable _Bash FAQ_ (on _Greg's Wiki_): [How can I calculate with floating point numbers?](http://mywiki.wooledge.org/BashFAQ/022)
*"For most operations... an external program must be used."*
+ From Mendel Cooper's wonderful and encyclopedic _Advanced Bash Scripting Guide_:
[Bash does not understand floating point arithmetic. Use bc instead.](https://tldp.org/LDP/abs/html/ops.html#NOFLOATINGPOINT)
+ From a community discussion on Stack Overflow, _How do I use floating point division in bash?_
The user's [preferred answer](https://stackoverflow.com/questions/12722095/how-do-i-use-floating-point-division-in-bash#12722107)
is a good example of _prevailing thought_ on this subject.
Meanwhile,
+ Bash maintainer (BDFL?) Chet Ramey sounds a (brighter?) note in [The Bash Reference Guide, Section 6.5](https://tiswww.case.edu/php/chet/bash/bashref.html#Shell-Arithmetic)
by emphasizing what the built-in arithmetic operators ***can*** do.
But finally, a glimmer of hope:
+ A [diamond-in-the-rough](http://stackoverflow.com/a/24431665/3776858) buried elsewhere
on Stack Overflow.
This down-and-dirty milestone computes the decimal quotient of two integer arguments. At a casual
glance, it seems to have drawn inspiration from the [Euclidean algorithm](https://mathworld.wolfram.com/EuclideanAlgorithm.html)
for computing GCDs, an entirely different approach than `shellmath`'s.
Please try `shellmath` on for size and draw your own conclusions!
## How it works
`shellmath` splits decimal numbers into their integer and fractional parts,
performs the appropriate integer operations on the parts, and recombines the results.
(In the spirit of Bash, numerical overflow is silently ignored.)
Because if we can get carrying, borrowing, place value, and the distributive
law right, then the sky's the limit! As they say--erm, as they ___said___ in Rome,
Ad astra per aspera.
## And now...
You can run your floating-point calculations directly in Bash!
## Please see also:
[A short discussion on arbitrary precision and shellmath](https://github.com/clarity20/shellmath/wiki/Shellmath-and-arbitrary-precision-arithmetic)
没有合适的资源?快使用搜索试试~ 我知道了~
bash-5.2.9.tar.gz
需积分: 1 0 下载量 99 浏览量
2024-01-30
00:31:18
上传
评论
收藏 10.44MB GZ 举报
温馨提示
共1441个文件
sub:392个
c:272个
h:120个
Bash 是一种广泛使用的 Unix shell,它是一个命令语言解释器,允许用户通过命令行界面与操作系统交互。Bash 同时是许多类 Unix 系统(如 Linux 和 macOS)的默认 shell,并且支持多种脚本编程功能。 Bash 作为一个强大的命令行工具,不仅用于日常的文件管理和系统操作任务,而且在自动化脚本、任务调度和高级编程方面也非常有用。它的灵活性和易用性使其成为开发者和系统管理员的首选 shell。
资源推荐
资源详情
资源评论
收起资源包目录
bash-5.2.9.tar.gz (1441个子文件)
bash.0 452KB
builtins.0 145KB
rbash.0 3KB
bashbug.0 2KB
bash.1 343KB
bashbug.1 2KB
builtins.1 883B
rbash.1 157B
test-minus-e.1 149B
test-minus-e.2 186B
ABOUT-NLS 92KB
configure.ac 41KB
locale.alias 3KB
array-at-star 2KB
array-stuff 2KB
array-to-string 340B
AUTHORS 17KB
autoload 3KB
basename 645B
arrayops.bash 3KB
notify.bash 1KB
spin.bash 1KB
aliasconv.bash 981B
bash-profile 887B
Bash_aliases 1KB
bash_completion 211KB
Bash_profile 339B
bashrc 2KB
bcalc 3KB
Bashrc.bfox 2KB
bison 823B
subst.c 361KB
y.tab.c 286KB
execute_cmd.c 171KB
variables.c 167KB
jobs.c 135KB
bashline.c 132KB
display.c 115KB
complete.c 88KB
man2html.c 83KB
bind.c 77KB
shell.c 58KB
vi_mode.c 55KB
snprintf.c 51KB
pcomplete.c 46KB
arrayfunc.c 45KB
readline.c 44KB
redir.c 43KB
trap.c 43KB
glob.c 42KB
histexpand.c 42KB
text.c 42KB
mkbuiltins.c 42KB
plural.c 41KB
malloc.c 40KB
print_cmd.c 40KB
emacs_keymap.c 37KB
expr.c 36KB
vi_keymap.c 36KB
getconf.c 35KB
general.c 34KB
loadmsgcat.c 34KB
dcigettext.c 33KB
bashhist.c 29KB
array2.c 28KB
array.c 28KB
sm_loop.c 28KB
isearch.c 26KB
common.c 25KB
terminal.c 24KB
nojobs.c 24KB
strftime.c 24KB
evalstring.c 24KB
input.c 23KB
rltty.c 23KB
make_cmd.c 23KB
localename.c 22KB
histfile.c 22KB
test.c 21KB
sig.c 21KB
kill.c 20KB
signals.c 20KB
braces.c 20KB
findcmd.c 20KB
misc.c 19KB
search.c 19KB
termcap.c 17KB
input.c 16KB
locale.c 16KB
history.c 15KB
pathexp.c 15KB
smatch.c 15KB
alias.c 15KB
alloca.c 14KB
cut.c 13KB
parse-colors.c 13KB
tilde.c 13KB
tilde.c 13KB
assoc.c 13KB
relocatable.c 12KB
共 1441 条
- 1
- 2
- 3
- 4
- 5
- 6
- 15
资源评论
程序员Chino的日记
- 粉丝: 2701
- 资源: 3万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
- 青岛大学人工智能实验二 利用α-β搜索的博弈树算法编写一字棋游戏
- ### 1、项目介绍 本项目Scrapy进行数据爬取,并使用Django框架+PyEcharts实现可视化大屏 效果如下:
- # 微信小程序-健康菜谱 基于微信小程序的一个查找检索菜谱的应用 ### 效果 !动态图(./res/gif/demo
- zabbix-get命令包资源
- 289ssm-mysql-jsp 计算机课程实验管理系统.zip(可运行源码+数据库文件+文档)
- 毕业设计,基于PyQt5实现的可视化界面的Python车牌自动识别系统源码
- 20-天天果园项目.rar
- 26-朴素贝叶斯分类.rar
- 没有安Matlab 也可以 生成FIR抽头系数工具.py
- 自助购药小程序源代码含文档
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功