1

I am trying to find the cube root of a number by bisecting it and then narrowing it down. I have the program for the square root in that way, but the cube root method simply continues to loop and never gives an answer. I am not sure where I have gone wrong and need some advice.

public class myFunc
{
    public static double squareRoot(double value, double precision)
    {
        double low, high, middle;
        high = 1;
        low = value;
        middle = (high + low) / 2;
        Console.WriteLine("{0,20:n12}{1,20:n12}{2,20:n12}", low, middle, high);
        while ((high-low)>precision)
        {
            if ((middle * middle) <value)
            {
                low = middle;
            }
            else
            {
                high = middle;
            }
            middle = (high + low) / 2;
            Console.WriteLine("{0,20:n12}{1,20:n12}{2,20:n12}", low, middle, high);
        }
        return (middle);
    }

    public static double cubeRoot(double value, double precision)
    {
        double low, high, middle;

        high = value;
        low = 1;
        middle = (high + low) / 3;
        Console.WriteLine("{0,20:n12} {1,20:n12} {2,20:n12}", low, middle, high);
        while ((high - low) > precision)
        {
            if ((middle * middle*middle)>value)
            {

                high = middle;
            }

            else
            {
                low = middle;
            }
            middle = (high + low) / 3;
            Console.WriteLine("{0,20:n12} {1,20:n12} {2,20:n12}", low, middle, high);
        }
        return (middle);
    }
Lutz Lehmann
  • 25,219
  • 2
  • 22
  • 51
Mokonalove
  • 19
  • 3
  • One of them uses high=1 and the other uses low=1. That's probably where your infinite loop comes from. – João Mendes May 06 '19 at 10:20
  • Possible duplicate of [Infinite loop when trying to find cube root of a non-perfect cube through bisection search](https://stackoverflow.com/questions/55315519/infinite-loop-when-trying-to-find-cube-root-of-a-non-perfect-cube-through-bisect) – Lutz Lehmann May 06 '19 at 10:23

1 Answers1

0

middle = (high + low) / 3; let's say high is 10, low is 8, middle is... 6? Isn't that outside the range you wanted?

The middle should still be (high + low) / 2, what is making this search for the third root is just the (middle * middle*middle)>value test.