Implement square root function.
Table of Contents
Square root using binary search:
#include <iostream>
#include <cmath>
double customSqrt(double x, double epsilon = 1e-6) {
if (x < 0.0) {
std::cerr << "Square root is undefined for negative numbers.\n";
return std::numeric_limits<double>::quiet_NaN(); // Return NaN for undefined result
}
// Handle special cases: square root of 0 or 1
if (x == 0.0 || x == 1.0) {
return x;
}
double low = 0.0;
double high = x;
// Perform binary search until the range is small enough
while (high - low > epsilon) {
double mid = (low + high) / 2.0;
double square = mid * mid;
if (square < x) {
low = mid;
} else {
high = mid;
}
}
return low + (high - low) / 2.0; // Final approximation
}
int main() {
// Test the custom square root function
double number;
std::cout << "Enter a number: ";
std::cin >> number;
double customResult = customSqrt(number);
double stdResult = std::sqrt(number);
std::cout << "Custom square root: " << customResult << "\n";
std::cout << "std::sqrt result: " << stdResult << "\n";
return 0;
}
Square root using Newton-Raphson method:
#include <iostream>
//using Newton-Raphson method.
double customSqrt(double x) {
// Initial guess
double guess = x / 2.0;
// Iterate until convergence or a maximum number of iterations
for (int i = 0; i < 100; ++i) {
// Update the guess using the Newton-Raphson formula
guess = 0.5 * (guess + x / guess);
}
return guess;
}
int main() {
// Test the custom square root function
double number;
std::cout << "Enter a number: ";
std::cin >> number;
if (number < 0) {
std::cout << "Square root is undefined for negative numbers.\n";
} else {
double result = customSqrt(number);
std::cout << "Custom square root of " << number << " is approximately: " << result << "\n";
}
return 0;
}