已知一個正數N的平方根介於0與N之間,根據二分逼近法,可令N的平方根為X(0<=X<=N),令a=0(下邊界),b=N(上邊界)
step 1: X=(a+b)/2
step 2: 若 X*X > N 則 令 a=a,b=X 反之 X*X < N 則 令 a=x,b=b 回step 1
step 3: 重複執行step 1跟step 2直到 X*X -> N
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim a, b, x, n As Double
Dim i As Integer
a = 0
n = Val(TextBox2.Text)
b = n
For i = 1 To b * 2 Step 1
x = ((a + b) / 2) '//尋找上下邊界的中間值
If ((x * x) >= n) Then '//如果X^2大於N^2則
b = x '//上邊界移動到中間值
TextBox4.Text &= "b=" & b.ToString("#.#####") & vbCrLf
ElseIf ((x * x) <= n) Then '//如果X^2小於N^2則
a = x '//下邊界移動到中間值
TextBox4.Text &= "a=" & a.ToString("#.######") & vbCrLf
End If
Next
TextBox3.Text = x.ToString("#.#####")
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
End
End Sub
End Class
沒有留言:
張貼留言