Presentation is loading. Please wait.

Presentation is loading. Please wait.

軟體實驗:實作以二分法開根號 虞台文. The Lab Problem Write a function to compute by bisection the square root of a positive integer n given by the caller. The function’s.

Similar presentations


Presentation on theme: "軟體實驗:實作以二分法開根號 虞台文. The Lab Problem Write a function to compute by bisection the square root of a positive integer n given by the caller. The function’s."— Presentation transcript:

1 軟體實驗:實作以二分法開根號 虞台文

2 The Lab Problem Write a function to compute by bisection the square root of a positive integer n given by the caller. The function’s prototype is double sqrt(int n). The algorithm proceeds as follows: Start with n and 1 as the upper and lower bounds, and then find the midpoint of the two bounds. If the square of the midpoint is equal or very close to n, then returns the midpoint as the answer and the algorithm terminates. If the square of the midpoint is greater than n, then let the upper bound be the midpoint; otherwise let the lower bound be the midpoint. Repeat the process until the estimates of the square root of n is within 0.000005 of each other. Returns the last estimate as the answer and the algorithm terminates. You can also define some functions for help if they make your code clearer. Verify that your code is correct. (sqrt.c)

3 double sqrt(int n) lowboundupbound 1 n mid mid 2  n return mid mid 2 > n upbound = mid mid 2 < n lowbound = mid mid = (lowbound + upbound)/ 2.0 What is then going on?


Download ppt "軟體實驗:實作以二分法開根號 虞台文. The Lab Problem Write a function to compute by bisection the square root of a positive integer n given by the caller. The function’s."

Similar presentations


Ads by Google