[Solved] C# logic (solution needed in coding) [closed]


The only tricky thing here is a comparison with tolerance, since because of round up errors you can well never meet

  answer == value

condition. The implementation could be

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

The actual answer (prove it) is just a square root:

  // 11.09053650640941716205160010261...
  Console.Write(Math.Sqrt(123));

Real life implementation (if my boss wants me to implement it):

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

9

solved C# logic (solution needed in coding) [closed]