[英]Cube Root using iterations and bisection
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);
}
middle = (high + low) / 3;
let's say high is 10, low is 8, middle is... 6? 假设高是10,低是8,中是... 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. 中间值仍应为
(high + low) / 2
,此搜索第三个根的原因只是(middle * middle*middle)>value
测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.