1
0

added argv support to the sqrt program

This commit is contained in:
Stephen M. McQuay 2012-08-28 21:35:32 -06:00
parent 957780462f
commit 411e266c4d

View File

@ -3,8 +3,11 @@ package main
import (
"fmt"
"math"
"os"
"strconv"
)
const usage = "usage: sqrt <number>"
const min_threshold = 1e-200
type ErrNegativeSqrt float64
@ -32,16 +35,24 @@ func Sqrt(x float64, threshold float64) (z float64, iterations int, err error) {
}
func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "%v\n", usage)
os.Exit(1)
}
i, err := strconv.ParseFloat(os.Args[1], 32)
if err != nil {
panic(err)
}
threshold := 1.0
right_answer := math.Sqrt(2)
right_answer := math.Sqrt(i)
for threshold > min_threshold {
answer, iterations, err := Sqrt(2, threshold)
answer, iterations, err := Sqrt(i, threshold)
if err != nil {
panic(err)
}
fmt.Printf("%0.4g %0.4g %0.20f %0.20f %0.2d\n",
threshold, right_answer-answer, right_answer, answer,
iterations)
fmt.Printf("%0.4g %0.2d %0.20f %0.20f %0.4g\n",
threshold, iterations, right_answer, answer,
right_answer-answer)
threshold = threshold / 10.0
}
}