简体   繁体   English

如何计算 shell 中的幂和根?

[英]How to compute exponentiation and roots in the shell?

I'm a beginner in shell and linux in general, it's a Shell Arithmetic question and I can't figure out what to write in terminal to solve these three equations.我是 shell 和 linux 的初学者,一般来说,这是一个 Shell 算术问题,我不知道在终端中写什么来解决这三个方程。 I'm sorry if it seems a bad question, I tried echo command and expr , but all of them are wrong and with many different errors like, '(', syntax error near..., E0F, and many other unfortunately. I hope someone will provide me with the correct commands. And I appreciate any help from you. I'll put down the terminal codes that I used which are wrong as I know.很抱歉,如果这似乎是一个不好的问题,我尝试了 echo command 和expr ,但所有这些都是错误的,并且有许多不同的错误,例如'(',语法错误...,E0F,以及许多其他不幸的错误。我希望有人能为我提供正确的命令。感谢您的帮助。我会记下我使用的终端代码,因为我知道这些代码是错误的。

$ x=8
$ y=21
$ echo $((2*x**3 + sqrt(y/2))
bash: unexpected EOF while looking for matching ')'
bash: syntax error: unexpected end of file
$ echo $((2*x**3) + (sqrt(y/2)))
bash: command substitution: line 1: syntax error near unexpected token +'
bash: command substitution: line 1: `(2*x**3) + (sqrt(y/2))'
$ echo $((2*x**3)+(sqrt(y/2))
bash: unexpected EOF while looking for matching )'
bash: syntax error: unexpected end of file
$ echo $((2*x**3)+(sqrt(y/2)))
bash: command substitution: line 1: syntax error near unexpected token +(sqrt(y/2))'
bash: command substitution: line 1: `(2*x**3)+(sqrt(y/2))'
$ echo $((2x**3)+(sqrt(y / 2)))
bash: command substitution: line 1: syntax error near unexpected token +(sqrt(y / 2))'
bash: command substitution: line 1: (2x**3)+(sqrt(y / 2))'

The shell is not the right tool to do floating point computations. shell 不是进行浮点计算的正确工具。 It only does integer math and does not provide functions like square root.它只进行 integer 数学运算,不提供平方根等函数。

However, the bc utility does both.但是,bc 实用程序两者兼而有之。 It is an arbitrary-precision decimal arithmetic language and calculator.它是一种任意精度的十进制算术语言和计算器。

$ bc
>>> scale=5
>>> sqrt(21)
4.58257
>>> scale=19
>>> sqrt(21)
4.5825756949558400065
>>> x=8
>>> y=21
>>> x+5
13
>>> x^2
64
>>> 2*x^2 - sqrt(y/2)
124.7596296507960698846
>>> Type Control-D to exit interactive bc.
$

Be sure to read the manual page for bc with man bc to understand all of its capabilities and limitations.请务必使用man bc阅读 bc 的手册页,以了解其所有功能和限制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM