Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Using binary search/interval halving, write a method that will guess the root of

ID: 3550737 • Letter: U

Question

Using binary search/interval halving, write a method that will guess the root of a number (JAVA)

We will be provided the following method where int n is the number and p is the power you want the number to be raised to..

I was thinking something along the lines of setting the high to n and the low to 0.  The middle of the interval would then be n/2 = some number...  Use this result raised to a power of r.. if is bigger than our high, which cannot be.  So the low stays at 0, and the high is now set to n/2 and so on.  I just can't understand how to implement it.

Explanation / Answer

import java.io.*;
import java.util.*;
import javax.swing.*;

public class Main
{
    public static double pow(double x,int r)
    {
        int i;
        double temp = 1;

        for(i= 0 ;i<r ; i++)
            temp = temp * x;
   
        return temp;
    }

    public static void main(String[] args)
    {
        int n,r;
        String s;
        s = JOptionPane.showInputDialog("Enter number: ");
        n = Integer.parseInt(s);
        s = JOptionPane.showInputDialog("Enter which root you want to calculate: ");
        r = Integer.parseInt(s);
        double high = n/2;
        double low = 0;
        double mid=0;
        double ans=0;
        double error=0;
        do
        {
            mid = (high + mid)/2.0;
            ans = pow(mid,r);
            if(ans > n)
                high = mid;
            else if(ans < n)
                low = mid;

            error = ans - n;
            if(error < 0)
                error = error * (-1);

        }while(error > 0.1);

        JOptionPane.showMessageDialog(null,"Root of number is " + mid);
    }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote