Java language Approximating a Square Root Using a Loop Out: 10/4 Due: 10/15 by 1
ID: 3593062 • Letter: J
Question
Java language
Approximating a Square Root Using a Loop Out: 10/4 Due: 10/15 by 11:50 PM Using Iteration, More on Basic Arithmetic Operations, More on Decision Statements, and More on Writing Interactive Programs Definition 1. A quare root of a number n is a number s such that In this project, you will use a loop to approximate the square root ofa number. There is an elementary algorithm used to find the square root of a number that takes advantage of a mathematical principle commonly referred to as the pinching (a.k.a. squeezing or sanduwrich) theorem. The theorem simply means that given any closed continuous interval [a, bl, there is a number p such that a 100, so we narrow the interval to [1, 13.375], the lower half of the interval. 7.1875×7.1875 100, so we narrow the interval to its lower half, (7.1875, 10.28125], etc. we will eventually obtain a midpoint whose square gives us 100. Due to truncation and roundoff errors by computers, Duncan Fall 2017Explanation / Answer
#include <iostream>
#include <string>
#define EPSILON 0.0000001 // least minimum value for comparison
using namespace std;
class test
{
public:
double SqRoot(double num) //function to cal square root
{
double low = 0; //variable declaration
double high = num;
double midPoint = 0;
while (high - low > EPSILON)
{
midPoint = low + (high - low) / 2; // finding mid value
if (midPoint*midPoint > num) //checking for condtion
{
high = midPoint;
} else
{
low = midPoint;
}
cout<<"[ "<<low<<","<<high<<" ]"<<endl; //printing the current range
}
return midPoint; //returning the value
}
};
int main()
{
double r,n;
cout << "Enter a number to find its square root -> "; //accepting number from user
cin>>n;
cout<<" "
test obj; //object of the class
r=obj.SqRoot(n);
cout<<"The square root of "<<n<<" is "<<r; //displaying the result
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.