implement of sqrt without using stdlib

来源:互联网 发布:go语言http json数据 编辑:程序博客网 时间:2024/06/11 13:42
/** binary search using  */// sqrt.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include <iostream>#include <cstdlib>#include <cassert>using namespace std;double mySqrt(double num, double delta){assert(num >= 1.0);double start = 1.0;double end = num;while(1){double mid = (start + end) / 2;double square = mid * mid;double tmp = (square>num) ? (square-num) : (num-square);if(tmp < delta) return mid;else if(square > num)end = mid;elsestart = mid;}}int main(int argc, char* argv[]){double num, delta = 0.001;while(true){cin>>num;if(num == 0)break;cout<<mySqrt(num, delta)<<endl;}//printf("Hello World!\n");return 0;}


 

/** Using Newton's method to implement sqrt() method.** Only process the case: input num > 0,* and resturn the positive square root.*/#include <iostream>#include <cmath>using namespace std;int main(){    double num;    cin >> num;    double res = 1.0;    while(abs(res*res - num) > 1e-5)    {        res = (res + num/res) / 2;    }    cout << fabs(res) << endl;    //cout << "Hello world!" << endl;    return 0;}

原创粉丝点击