added argv support to the sqrt program
This commit is contained in:
parent
957780462f
commit
411e266c4d
|
@ -3,8 +3,11 @@ package main
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
|
"os"
|
||||||
|
"strconv"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
const usage = "usage: sqrt <number>"
|
||||||
const min_threshold = 1e-200
|
const min_threshold = 1e-200
|
||||||
|
|
||||||
type ErrNegativeSqrt float64
|
type ErrNegativeSqrt float64
|
||||||
|
@ -32,16 +35,24 @@ func Sqrt(x float64, threshold float64) (z float64, iterations int, err error) {
|
||||||
}
|
}
|
||||||
|
|
||||||
func main() {
|
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
|
threshold := 1.0
|
||||||
right_answer := math.Sqrt(2)
|
right_answer := math.Sqrt(i)
|
||||||
for threshold > min_threshold {
|
for threshold > min_threshold {
|
||||||
answer, iterations, err := Sqrt(2, threshold)
|
answer, iterations, err := Sqrt(i, threshold)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
fmt.Printf("%0.4g %0.4g %0.20f %0.20f %0.2d\n",
|
fmt.Printf("%0.4g %0.2d %0.20f %0.20f %0.4g\n",
|
||||||
threshold, right_answer-answer, right_answer, answer,
|
threshold, iterations, right_answer, answer,
|
||||||
iterations)
|
right_answer-answer)
|
||||||
threshold = threshold / 10.0
|
threshold = threshold / 10.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue