Skip to content

Instantly share code, notes, and snippets.

@lukewilson2002
Last active September 15, 2019 21:12
Show Gist options
  • Save lukewilson2002/9b2dc584f141534ad232b9c884da2bab to your computer and use it in GitHub Desktop.
Save lukewilson2002/9b2dc584f141534ad232b9c884da2bab to your computer and use it in GitHub Desktop.
A program to compute inverses of numbers (requires Go 1.13+ for floating-point hex)
package main
import (
"fmt"
"os"
"strconv"
)
const (
eps1m01 float64 = 1.0 - 0x1P-01
eps1p01 float64 = 1.0 + 0x1P-01
eps1m24 float64 = 1.0 - 0x1P-24
eps1p24 float64 = 1.0 + 0x1P-24
)
func main() {
for i := 1; i < len(os.Args); i++ { // Process args
a, _ := strconv.ParseFloat(os.Args[i], 64) // arg -> double
x := 1.0
for { // By powers of 2
prod := a * x
if prod < eps1m01 {
x *= 2.0
} else if eps1p01 < prod {
x *= 0.5
} else {
break
}
}
for { // Heron approximation
prod := a * x
if prod < eps1m24 || eps1p24 < prod {
x *= 2.0 - prod
} else {
break
}
}
fmt.Printf("heron: a=%.5e,\tx=%.5e,\ta*x=%.12f\n", a, x, a*x)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment