Created
July 6, 2019 07:47
-
-
Save libook/0357e6e3b1e1c41dee248463efd890ee to your computer and use it in GitHub Desktop.
This file contains 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" | |
) | |
func Iteration(x, r float64) float64 { | |
//f(x)=x^2-r | |
//随机取的x,算出对应的y | |
y := x*x - r | |
//曲线方程的导函数是曲线上某一点的切线斜率 f'(x)=2x => 切线斜率=2x | |
k := 2 * x | |
//这一点同时在曲线上,也同时在切线上,两线x和y一样 | |
//曲线当前点上的切线方程为 y切线=kx切线-b,求b | |
//y=kx-b => b=kx-y | |
b := k*x - y | |
//当y切线为0的时候,求x切线 y=kx-b => x=(y+b)/k =y为0=> x=b/k | |
tangentLintX := b / k | |
return tangentLintX | |
} | |
func Sqrt(x float64) float64 { | |
times := 0 | |
guess := x / 2 | |
for { | |
times++ | |
guessThisTime := Iteration(guess, x) | |
if guess == guessThisTime { | |
fmt.Println(times) | |
return guessThisTime | |
} else { | |
guess = guessThisTime | |
} | |
} | |
} | |
func main() { | |
fmt.Println(Sqrt(5)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment