Storing a value obtained in a loop and using it in the same equation to get a result

For example if I am using the equation

[(x/y)+y] / 2 = z

How would I store the value of z in a for loop and use the value of z, for y in the same equation, please modify my code. I cannot use cmath.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
	double num, conv, old;
	int tries, x;

	cout << "Enter a value greater than 0: " << endl;
	cin >> num;

	cout << "How many times should we run this equation?" << endl;
	cin >> tries;

	old = num / 2;
	conv = ((num / old) + old) / 2;

	cout << "Try 0 = " << old << endl;

	for (x = 1; x <= tries; x++)
	{
		cout << "Try " << x << " = " << conv << endl;
	}

	system("pause");
}


So saving the value of conv, and replacing old with conv in the equation as many times as tries.

Enter a value greater than 0:
25
How many times should we run this equation?
5
Try 0 = 12.5
Try 1 = 7.25
Try 2 = 7.25
Try 3 = 7.25
Try 4 = 7.25
Try 5 = 7.25
Press any key to continue . . .
Last edited on
In your example you only did it once since it's outside the for loop. Either make a function or throw the whole equation inside the for loop.
I forgot to mention I cannot create a function.
So where should i go from here?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
	double num, conv, old;
	int tries, x;

	cout << "Enter a value greater than 0: " << endl;
	cin >> num;

	cout << "How many times should we run this equation?" << endl;
	cin >> tries;

	cout << "Try 0 = " << num / 2 << endl;

	for (x = 1; x <= tries; x++)
	{
		old = num / 2;
		conv = ((num / old) + old) / 2;

		cout << "Try " << x << " = " << conv << endl;
	}

	system("pause");
}


Enter a value greater than 0:
25
How many times should we run this equation?
5
Try 0 = 12.5
Try 1 = 7.25
Try 2 = 7.25
Try 3 = 7.25
Try 4 = 7.25
Try 5 = 7.25
Press any key to continue . . .



You are doing what is called "single-point iteration", and if you do it right you should end up with the square root of num.

conv and old are fundamentally the same variable: possibly successive iterates. You can work out the RHS of an equation and then reassign to the variable on the left.

- In your line 21, replace old by conv and then move this line before the loop: it is an initial value, set only once.
- Replace both occurrences of old in line 22 by conv: yes, you are allowed to do that; it's the whole point of the iteration.
- You should then be able to remove variable old completely.


ALTERNATIVELY (and I'm putting this here just in case you are told to use a non-deterministic loop in the future)
- put conv = num / 2; before the loop as an initial value.
- replace the current line 21 by old = conv; and leave the current line 22 as it is.
- you keep both old and conv this time, but you can then base your decision to continue looping on the difference between successive iterates, abs(conv-old), rather than having a fixed number of tries.
Last edited on
Ahh, this makes perfect sense. Thank you for helping me understand!
So, fixing the number of tries (deterministic loop) means you may do either an unnecessary number of iterations or you may not do enough. To base convergence on the difference between successive iterates you will have to store the previous iterate (the "ALTERNATIVELY" approach above). How many iterates it takes depends on the tolerance set (which is a bit tight below).

I don't do code-fixing by PM @JarJarz:
(a) I might inadvertently give bad advice; the forum at least gives a chance for others to correct it;
(b) the rest of your class is entitled to the same advice, for good or bad.


EDITED!! Don't use - see correction in later post (thanks to @doug4 for the correction).

#include <iostream>
#include <cmath>
using namespace std;

int ipow( int n, int p ) // n to the power p (positive integer) //ERROR: n and result should be integers {
int result = 1;
while ( p-- ) result *= n;
return result;
}


double nthroot( double num, int n ) // find nth root of num
{
double TOLERANCE = num / 1.0e10; // cut-off at this difference between successive iterates
int MAXITER = 1000; // cut-off on iterations if not converging
double x = num / n; // initial guess
double xold = x + 1.0; // anything not close to initial guess
int iter = 0; // iteration counter

while ( abs( x - xold ) > TOLERANCE && iter < MAXITER ) // conditions to keep looping
{
iter++;
xold = x; // store previous iterate
x = ( ( n - 1 ) * x + num / ipow( x, n - 1 ) ) / n; // iteration step (Newton-Raphson for f(x) = x^n - num)
cout << "Iteration " << iter << ": " << x << '\n'; // REMOVE FOR FINAL VERSION
}
return x;
}

int main()
{
int num, root; // ERROR; num should be double

cout << "Input number and root: ";
cin >> num >> root;
double value = nthroot( num, root );
cout << "------\n" << num << " to the power 1/" << root << " is " << value;
}
Last edited on
int ipow( int n, int p ) // n to the power p (both positive integers)

double x = num / n; // initial guess

x = ( ( n - 1 ) * x + num / ipow( x, n - 1 ) ) / n;

Was this intended? Or did you mean to write
1
2
3
double ipow(double n, int p )
{
    double result = 1;
?
Last edited on
I did indeed mean what you note, @doug4! Thank-you very much indeed for the correction!!! Also had an inconsistent type in main().

Revised version below. The original was terrible coding and checking on my part.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <cmath>
using namespace std;

//======================================================================

double ipow( double x, int p )                   // x to the power p (p is a positive integer)
{
   double result = 1;
   while ( p-- ) result *= x;
   return result;
}

//======================================================================

double nthroot( double num, int n )              // find nth root of num
{
   double TOLERANCE = num / 1.0e10;              // cut-off at this difference between successive iterates
   int    MAXITER   = 1000;                      // cut-off on iterations if not converging

   double x = num / n;                           // initial guess
   double xold = x + 1.0;                        // anything not close to initial guess
   int iter = 0;                                 // iteration counter

   while ( abs( x - xold ) > TOLERANCE && iter < MAXITER )           // conditions to keep looping
   {
      iter++;
      xold = x;                                                      // store previous iterate

      x = (  ( n - 1 ) * x + num / ipow( x, n - 1 )  ) / n;          // iteration step (Newton-Raphson for f(x) = x^n - num)

      cout << "Iteration " << iter << ":   " << x << '\n';           // REMOVE FOR FINAL VERSION
   }

   return x;
}

//======================================================================

int main()
{
   double num;
   int root;

   cout << "Input number and root: ";
   cin >> num >> root;

   cout.setf( ios::fixed );   cout.precision( 10 );
   double value = nthroot( num, root );

   cout << "------\n" << num << " to the power 1/" << root << " is " << value;
}

//====================================================================== 



Input number and root: 6.25 2
Iteration 1:   2.5625000000
Iteration 2:   2.5007621951
Iteration 3:   2.5000001162
Iteration 4:   2.5000000000
Iteration 5:   2.5000000000
------
6.2500000000 to the power 1/2 is 2.5000000000 


Input number and root: 625  4
Iteration 1:   117.1875409600
Iteration 2:   87.8907528103
Iteration 3:   65.9182947468
Iteration 4:   49.4392665694
Iteration 5:   37.0807429433
Iteration 6:   27.8136218141
Iteration 7:   20.8674782125
Iteration 8:   15.6678039738
Iteration 9:   11.7914781921
Iteration 10:   8.9389135528
Iteration 11:   6.9229441065
Iteration 12:   5.6631285297
Iteration 13:   5.1076480767
Iteration 14:   5.0033555993
Iteration 15:   5.0000033742
Iteration 16:   5.0000000000
Iteration 17:   5.0000000000
------
625.0000000000 to the power 1/4 is 5.0000000000
Last edited on
Registered users can post here. Sign in or register to post.