TurtleMan - 1 year ago 52

Linux Question

This is my first bash script and have ran into a little problem with setting the decimal precision. I have been tasked to create a bash script that calculates the area and circumference of a circle given the diameter of 20. This is what I currently have

`#!/bin/bash`

clear

diameter=$1 # storing first argument

radius=$(echo "scale=5;$diameter / 2" | bc) # setting radius

# echo "$radius"

# calculate area of a circle

area=$(echo "scale=5;3.14 * ($radius * $radius)" | bc -l) # A = pi(r^2)

# calculate circumference of a circle

circum=$(echo "scale=5;2 * 3.14 * ($radius)" | bc -l) # C = 2(pi)(r)

echo "Circumference: $circum"

echo "Area: $area"

When I run the script it prints out

`Circumference: 62.80000`

Area: 314.00000

It should be printing out

`Circumference: 62.83185`

Area: 314.15926

I am not understand why it is not displaying the correct decimal values. I have given the

`scale=5`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

If pi were equal to 3.14, then your code is giving exact results.

To get the exact value of pi in `bc`

code, use `4*a(1)`

:

```
# calculate area of a circle
area=$(echo "scale=5;4*a(1) * ($radius * $radius)" | bc -l) # A = pi(r^2)
# calculate circumference of a circle
circum=$(echo "scale=5;2 * 4*a(1) * ($radius)" | bc -l) # C = 2(pi)(r)
```

(This works because `a(1)`

is the arctangent of 1 which is pi/4.)

With those changes, a sample run looks like:

```
$ bash circ.sh 20
Circumference: 62.83120
Area: 314.15600
```

The limited precision now is due to the choice of `scale=5`

.

The code below keeps the best precision around until it is time to print and then prints in your desired precision:

```
#!/bin/bash
diameter=$1 # storing first argument
radius=$(echo "$diameter/2" | bc -l) # setting radius
# calculate area of a circle
area=$(echo "4*a(1)*$radius^2" | bc -l) # A = pi(r^2)
# calculate circumference of a circle
circum=$(echo "2 * 4*a(1) * $radius" | bc -l) # C = 2(pi)(r)
printf "Circumference: %.5f\n" "$circum"
printf "Area: %.5f\n" "$area"
```

Example:

```
$ bash circ.sh 20
Circumference: 62.83185
Area: 314.15927
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**