Question
(JAVA) Write a public class named MyMath. (So the filename must be MyMath.java.) The class MyMath should have exactly 2 member functions: sqrt and main.
(JAVA) Write a public class named MyMath. (So the filename must be MyMath.java.) The class MyMath should have exactly 2 member functions: sqrt and main.
Problem 1: (Square root) In this homework assignment, write a function that computes the square root of a given double up to a certain precision. This function should be a member function of of class MyMath and should have signature
public static double sqrt ( double d )
You will use a technique called bisection or binary search for its implementation. First assume the input, which we call d, is between 0 and 1. Then we know that l d u, where l = 0 and u = 1. Here, l represents a lower bound for the (yet unknown) value of d, and u represents an upper bound.
To perform bisection, take the midpoint m = (l +u)/2 and check whether d is within the interval [l, m] or [m, u]. To do so, check whether d m2 , since if d m2 then d m. If d m2 then d is in the interval [l, m]. So perform the update u = m. If m2 < d then d is in the interval [m, u]. So perform the update l = m.
By iterating this process, we get a successively tighter interval [l, u] that contains d. If the length of this interval is small enough, i.e., if ul is small enough, we terminate this process; the midpoint m = (l + u)/2 will be very close to the true value of d. For the purpose of this assignment, you can terminate when the interval is smaller than 1010 .
Finally, we have to deal with the case when d > 1. One way to handle this case is by normalizing the input. The approach is based on the simple insight
d = 2 ( d/4 )
d = (2^2) ( d/4 ^2)
d = (2^3) ( d/4^3)
. . .
So loop and divide d by 4 until you reach a value less than or equal to 1. Compute the square root of the dividend, and make sure to multiply back the appropriate power of 2. You may not use Math.sqrt in the implementation of MyMath.sqrt.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started