-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathsqrt.sh
executable file
·73 lines (57 loc) · 1.88 KB
/
sqrt.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/usr/bin/env bash
# Script Name: sqrt.sh
# Description: This script calculates the square root of a specified number.
# Usage: sqrt.sh number precision
# number - The number to compute the square root for.
# [precision] - The number of decimal places for rounding the result (optional).
# Example: ./sqrt.sh 16
# Output: 4
calculate_sqrt() {
local number=$1
local precision=$2
local scale
scale=$((precision + 1))
local guess
guess=$(bc -l <<< "$number / 2")
while true; do
local new_guess
new_guess=$(bc -l <<< "scale=$scale;($guess + $number / $guess) / 2")
local difference
difference=$(bc -l <<< "scale=$scale; $guess - $new_guess")
if (( $(echo "$difference < 0" | bc -l) )); then
difference=$(bc -l <<< "-1 * $difference")
fi
if (( $(echo "$difference < 1 * 10^-$scale" | bc -l) )); then
break
fi
guess=$new_guess
done
# Use bc to round the result
bc -l <<< "scale=$precision; $new_guess / 1"
}
main() {
if [[ $# -lt 1 || $# -gt 2 ]]; then
echo "Error: Invalid number of arguments provided."
echo "Usage: sqrt.sh number [precision]"
echo " number - The number to compute the square root for."
echo " [precision] - The number of decimal places for rounding the result (optional)."
exit 1
fi
local number="$1"
local precision=0
if [[ $# -eq 2 ]]; then
precision="$2"
fi
if [[ ! $number =~ ^[0-9]+(\.[0-9]+)?$ ]]; then
echo "Error: The provided number ($number) is not a positive number!"
exit 1
fi
if [[ ! $precision =~ ^[0-9]+$ ]]; then
echo "Error: The provided precision ($precision) is not a positive integer!"
exit 1
fi
local result
result=$(calculate_sqrt "$number" "$precision")
echo "$result"
}
main "$@"