使用迭代和二等分的立方根

时间:2019-03-01 07:47:02

标签: java root cube bisection

我试图通过将数字二等分然后缩小范围来找到它的立方根。我以这种方式有平方根的程序,但是立方根方法只是继续循环而从未给出答案。我不确定哪里出了问题,需要一些建议。

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);
    }

1 个答案:

答案 0 :(得分:0)

middle = (high + low) / 3;假设高是10,低是8,中是... 6?那不是您想要的范围吗?

中间位置仍然应该是(high + low) / 2,而对第三个根的搜索就是(middle * middle*middle)>value测试。