Iterating an unknown number in C #

Let's say I have a formula that contains a variable that the user has to guess. But at the end of the formula, this variable is calculated again, and if the first and second do not match, the formulation must be solved again with a new value. Soon, suppose I have a formula like this (mine is much more complicated and longer than this);

        double y1 = Convert.ToDouble(txtboxPredefinedY.Text);
        double x, z, Ort;
        double y2 = 0;

        while (y1 != y2)
        {
            x = (Math.Pow(y1, 2)) + 10;
            z = (y1 - 2) / 3;
            y2 = (x / z);

            Ort = (y2 + y1)/2;
            y1 = Ort;

            if (y1 == y2)
                break;
        }

        txtboxResult.Text = r.ToString();

      

So the variable y1

I defined must match the last variable y2

. To do this, I calculate the whole formula and find a new formula y1

, recalculated formula.

I want to determine the value y1

and have the application correct me. For example, this code should return a value to me 3.3158

. If the first input 3.3158

than y1

becomes equal y2

.

I couldn't use iteration correctly while

. How can I fix this? Or maybe how should I construct a block while

to give an exact equation?

+3


source to share


1 answer


When working with Double

you should compare with the tolerance :

  double y1 = Convert.ToDouble(txtboxPredefinedY.Text);
  double x, z, Ort;
  double y2 = 0;

  double tolerance = 0.001;

  while (Math.Abs(y1 - y2) >= tolerance)  {
    x = (Math.Pow(y1, 2)) + 10;
    z = (y1 - 2) / 3;
    y2 = (x / z);

    Ort = (y2 + y1)/2;
    y1 = Ort;
  }

      



Comparisons such as y1 != y2

and also y1 == y2

may not work due to rounding errors.

+5


source







All Articles