Approximating Square Roots Approximating a Square Root Using a Loop Out: 10/4 CS
ID: 3590218 • Letter: A
Question
Approximating Square Roots Approximating a Square Root Using a Loop Out: 10/4 CSc 1350: Programming Project # 2 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 square root of a number n is a number s such that S -m In this project, you will use a loop to approximate the square root of a 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 sanduwich) theorem. The theorem simply means that given any closed continuous interval [a.a. there is a number p such that a K p 100 so we choose the lower half of the interval, [1.25.75]. 13.375 × 13.375 > 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
Given below is the code with output. Please don't forget to rate the answer if it helped. Thank you.
To indent code in eclispe, select code by pressing Ctrl+A and then press Ctrl+ i
import java.util.Scanner;
public class SquareRootFinder {
public static void main(String[] args) {
double low, high, midPoint, midPointSqr;
final double EPSILON = 1E-6;
double n, squareRoot;
Scanner keybd = new Scanner(System.in);
System.out.print("Enter a number to find its square root: ");
n = keybd.nextDouble();
if(n < 0)
squareRoot = Double.NaN;
else
{
if(n < 1)
{
low = 0;
high = 1;
}
else
{
low = 1;
high = n;
}
int iteration = 1;
while(true)
{
System.out.printf("[%.6f, %.6f] ", low, high);
midPoint = (low + high) / 2;
midPointSqr = midPoint * midPoint;
if(Math.abs(midPointSqr - n) <= EPSILON)
{
squareRoot = midPoint;
break;
}
if(midPointSqr > n)
high = midPoint;
else
low = midPoint;
}
}
System.out.printf("The square root of %.6f is %.6f", n, squareRoot);
}
}
output
Enter a number to find its square root: 0.00390625
[0.000000, 1.000000]
[0.000000, 0.500000]
[0.000000, 0.250000]
[0.000000, 0.125000]
The square root of 0.003906 is 0.062500
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.