Given a non-negative number x, we want to approximate its square root in C++ without using the sqrt function from the ma

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

Given a non-negative number x, we want to approximate its square root in C++ without using the sqrt function from the ma

Post by answerhappygod »

Given a non-negative number x, we want to approximate its square
root in C++ without using the sqrt function from the math library
(we will use it only to compare its answer with our approximation).
For simplicity we will assume that x ≤ 1 and thus x ≤ √ x ≤ 1.
How to approximate the square root?
Approach 1: Exhaustive search
We know that the square root is in the interval [x, 1]
Divide the interval [x,1] into say 1000000 equally spaced
points
Sequentially loop over the points to find the point p such that
p*p is closest to x
Very slow!
Approach 2:
The bisection method
Compute the midpoint of the interval [x, 1]: mid = x+1 2
Compare mid ∗ mid with x: if mid ∗ mid < x, narrow down the
search to the interval [mid, 1], else, narrow it down to [x,
mid]
Repeat the above process until abs(mid∗mid−x) ≤ epsilon, where
epsilon is the approximation error margin that we will allow (e.g.,
you can take epsilon = 0.00001)
Write a C++ program that reads the value of x from the user and
prints an error message if the input is not in the valid range
(should be between 0 and 1). If the input is valid, compute and
print the approximate square root of x using the bisection method
described above. To verify the accuracy of your approximation, also
print the square root using the sqrt function from the math
library.
Hint: define two variables: low and high to keep track of the
boundaries of the search interval. Initially, low = x and high = 1.
As the algorithm proceeds, update these limits as needed. Submit
your solution in the source file bisection.cpp.
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply