我想像循环一样使用:示例 我在我的公式中放入文本框123和300。
1/2 *(300 + 123/300)= 150.205>答案
我想循环这个例子我得到答案150.205下一个公式应该看起来像这样
1/2 *(150.205 + 123 / 150.205)= 75.512
这个等式的答案我想通过循环放入下一个公式。
我已编写代码,但我不知道如何通过循环使用它
double value = (0.5 * (300 + 123 / 300));
=======================================
对于结束循环
条件匹配时这样 1/2 *(11.091 + 123 / 11.091)= 11.091 含义答案和输入我放300的地方将是相同的我想要打破循环
**Example** I want to do this without using square root function in c#
like simple if i want a root of 9 it will be 3 so it will be like this .
i choosen 1 Because 9 is one value so i choosen 1
1/2*(1+9/1) = 5.000
1/2*(5+9/5) = 3.400
1/2*(3.4+9/3.4) = 3.024
1/2*(3.024+9/3.024) = 3.000
1/2*(3+9/3) = 3.000
see you will get same value in one point always
答案 0 :(得分:1)
这里唯一的棘手的事情是与容差的比较,因为汇总错误你可以永远 em>见面
answer == value
条件。实施可能是
double answer = 300.0;
double tolerance = 1e-10;
while (true) {
// based on previous answer we compute next one
double value = 0.5 * (answer + 123.0 / answer);
//TODO: you can print out steps here, if you want something like this
//Console.WriteLine(value);
// check convergence with tolerance
if (Math.Abs(answer - value) <= tolerance) {
answer = value;
break;
}
// next answer (value) becomes the previous one (answer)
answer = value;
}
// 11.0905365064094
Console.Write(answer);
实际答案(证明它)只是平方根:
// 11.09053650640941716205160010261...
Console.Write(Math.Sqrt(123));
现实生活(如果我的老板要我实施它):
public static double NewtonEstimation(Func<double, double> function,
double tolerance = 1e-10,
double guess = 1.0) {
if (null == function)
throw new ArgumentNullException("function");
else if (tolerance < 0)
throw new ArgumentOutOfRangeException("tolerance", "tolerance must not be negative");
while (true) {
double value = function(guess);
if (Math.Abs(value - guess) <= tolerance)
return value;
guess = value;
}
}
...
// 11.0905365064094
Console.Write(NewtonEstimation(x => 0.5 * (x + 123 / x)));