我想使用如下循环:例如,我在公式中的文本框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
唯一棘手的事情是将公差与公差进行比较,因为由于舍入误差,您可能永远无法满足
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)));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句