0

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. 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.

$ 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))'
Jens
  • 69,818
  • 15
  • 125
  • 179
James1970
  • 11
  • 1
  • My apologies, I forgot to write the question, don't mind me. Thank You! Q // If X=8, and Y=21, Find the exact result of the following expressions : • X^2 + Y-5 • 2X^3 + √Y /2 • Y^2/ (X+5)^2 – James1970 May 25 '21 at 01:34
  • Welcome to Stack Overflow! Please take the [tour] and read [ask]. Please don't use comments to add to the question, instead [edit] the question itself. While you're there, please fix the [code formatting](/editing-help#code). – wjandrea May 25 '21 at 02:40
  • I don't believe most shells have `sqrt` built-in. You could try passing to `bc`. However, what do you think the **exact result** of `sqrt(21/2)` (or even `sqrt(21)/2`) should be? – jhnc May 25 '21 at 04:43

1 Answers1

1

The shell is not the right tool to do floating point computations. It only does integer math and does not provide functions like square root.

However, the bc utility does both. 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.

Jens
  • 69,818
  • 15
  • 125
  • 179