Python计算器 - 隐式数学模块

12

有时我需要计算某些东西的答案。由于我通常会打开终端屏幕,这是我询问此类数学问题的自然场所。

Python交互式shell非常适合这个目的,前提是你想要进入另一个shell,只是稍后又必须退出它。

但有时最好能够立即从命令行获得答案。Python具有-c命令选项,我发现它在处理单个命令并返回结果方面非常有用。我编写了以下bash shell脚本来利用它:

#!/bin/bash
# MHO 12-28-2014
#
# takes a equation from the command line, sends it to python and prints it
ARGS=0
#
if [ $# -eq 1 ]; then
  ARGS=1
fi
#
if [ $ARGS -eq 0 ]; then
  echo "pc - Python Command line calculator"
  echo "ERROR: pc syntax is"
  echo "pc EQUATION"
  echo "Examples"
  echo "pc 12.23+25.36      pc \"2+4+3*(55)\""
  echo "Note: if calculating one single equation is not enough,"
  echo "go elsewhere and do other things there."
  echo "Enclose the equation in double quotes if doing anything fancy."
  echo "m=math module ex. \"m.cos(55)\""
  exit 1
fi
#
if [ $ARGS -eq 1 ]; then
  eqn="$1"
  python -c "import math; m=math; b=$eqn; print str(b)"
fi
#

示例输出

$ pc 1/3.0
0.333333333333
$ pc 56*(44)
2464
$ pc 56*(44)*3*(6*(4))
177408
$ pc "m.pi*(2**2)"
12.5663706144

请注意python -c选项,有没有一种简洁的方式可以隐式地引用math模块,以便最后的pc命令可以格式化为pc"pi*(2 ** 2)"


1
你可以简化为 python -c "from math import *; print $eqn"。顺便说一句,与其在你的 bash 脚本中使用无数个 echo 命令,不如使用 heredoc。还要注意一下任意精度计算器 bc,虽然语法不如 Python 那么好看,但它几乎在所有 Linux 系统上都通用。 - PM 2Ring
1
不错的工具,你应该把它放在GitHub上 :) - Håkon Hægland
2
不错,但是使用bc会更简单吧?例如像这样:bc -l <<< "4*a(1) * (2^2)" - user000001
2个回答

17

你可以使用

from math import *

将math模块中的所有常量和函数导入到全局作用域中。


4
if [ $ARGS -eq 1 ]; then
  eqn="$1"
  python -c "from math import *; b=$eqn; print str(b)"
fi

$ pc "pi*(2**2)"
12.5663706144

太好了!谢谢!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接