Created
December 30, 2021 08:24
-
-
Save itherunder/27f90dc9abfa90bda328053a3d6c5b6c to your computer and use it in GitHub Desktop.
牛顿法求sqrt,就是拿表达式去逼近0,然后每次更替的时候就需要除以表达式的导数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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