Skip to content

Instantly share code, notes, and snippets.

@itherunder
Created December 30, 2021 08:24
Show Gist options
  • Save itherunder/27f90dc9abfa90bda328053a3d6c5b6c to your computer and use it in GitHub Desktop.
Save itherunder/27f90dc9abfa90bda328053a3d6c5b6c to your computer and use it in GitHub Desktop.
牛顿法求sqrt,就是拿表达式去逼近0,然后每次更替的时候就需要除以表达式的导数
package main
import (
"fmt"
"math"
)
func Sqrt(x float64) float64 {
var z float64 = 1
for math.Abs(z*z-x) > 0.0001 {
fmt.Println(z)
z -= (z*z - x) / (2 * z)
}
return z
}
func main() {
fmt.Println(Sqrt(12))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment