Implement SQRT () Functions

Source: Internet
Author: User

Evaluate the square of a positive number N and specify the precision. The library function SQRT must not be used.

Method 1: first calculate the integer part of SQRT (N), then calculate the first digit after the decimal point, two digits ......

Method 2: Newton Iteration Method, according to the formula ai + 1 = (AI + number/AI)/2, where the initial value of AI is A1, such as 1, 2, 3...

// Calculate the start of a positive number N and specify the precision. You must not use the library function SQRT # include <stdio. h> # include <stdlib. h> double my_sqrt2 (double number, int point) {double new_guess; double last_guess; If (number <0) {printf ("cannot compute the square root of a negative number! \ N "); Return-1;} printf (" Method 2: \ n "); new_guess = 1; do {last_guess = new_guess; new_guess = (last_guess + number/last_guess) /2; printf ("%. * lf \ n ", point, new_guess);} while (new_guess! = Last_guess); Return new_guess;} double my_sqrt1 (double N, int point) {If (n <0) {printf ("cannot compute the square root of a negative number! \ N "); Return-1;} int I, j; for (I = 1; I-n <0; I ++) // obtain the integer portion of the open I if (I * I-n> 0) break; double answer = I-1; double incr = 0.1; For (j = 1; j <= point; j ++) // obtain the J-digit {for (I = 1; I <10; I ++) {answer + = incr; If (answer * answer-N> 0) break;} answer-= incr; incr/= 10;} incr * = 10; printf ("Method 1: \ n"); printf ("SQRT (% lf) is between %. * lf-%. * lf \ n ", N, point, answer, point, answer + incr); Return answer;} int main (void) {int point; Double N; printf ("enter a positive integer N:"); scanf ("% lf", & N); printf ("Enter the digits accurate to the decimal point :"); scanf ("% d", & Point); my_sqrt1 (n, point); my_sqrt2 (n, point); Return 0 ;}

 

Implement SQRT () Functions

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.