views:

177

answers:

2

I'm trying to implement an algorithm we did in numerical methods class. I have an identical procedure written in Maple and it works fine. I can't understand why it isn't working in C++.

Any help or tips would be appreciated; thanks in advance.

#include "stdafx.h"
#include "math.h"
#include <iostream>

using namespace std;

double absval(double val)
{
   if (val >= 0) return val;
   else return -val;
}
double G(double x)
{
   double g;

   g = 1/((x*x)+12);
   return g;
}
int main()
{
double c = 0.011834; /* constant */
double eps = 0.00001; /* precision */
double x0 = 0; /* initial aproximation */
double x1,x2,c1;
int i,no;
i = 1;

cout << "enter max nr of iterations ";
cin >> no; 

x1 = x0;
x2 = G(x1);
c1 = (1-c)*eps/c;

while (absval(x1-x0) > c1)
{
    i = i+1;
    x1 = x2;
    x2 = G(x1);

}
cout << x2;
if (i<no) cout << " solution found in allowed nr of iterations ";
else cout << "allowed nr of iterations surpassed ";

}

When running the code it asks for the allowed number of iterations and after inserting that it closes.

+2  A: 

I tried it and it does work.

0.0833333 solution found in allowed nr of iterations

EDIT(s):

You might want to change the design so that it checks i each time around the loop though, instead of waiting until it has the answer. As it is, if the iteration diverges it could go on forever.

Oh, yes, and as moonshadow says the loop is never entered :D

I think you're comparing the wrong things? Is this right (testing x1-x2, instead of x1-x0):

...

do 
{
    x1 = x2;
    x2 = G(x1);
} while (i++ < no && absval(x1-x2) > c1);


cout << x2 << endl;
if (i<no) cout << " solution found in allowed nr of iterations " << endl;
else cout << "allowed nr of iterations surpassed " << endl;


cout << "Press enter to exit." << endl;
cin.get();
Autopulated
0.0833333 is the correct solution that maple gives. I've changed with do while and it still doesn't work, can you post the full program.This is the maple procedure I used:mas:=proc(g,x0,c,eps)> local x1,x2,c1;> x1:=x0;> x2:=g(x1);> print(evalf(x2));> c1:=(1-c)*eps/c:> while abs(x1-x0)>c1 do> x1:=x2;> x2:=g(x1);> print(evalf(x2));> od;> end;c2:=2/169;x0:=0;eps:=10^(-6);mas(g,x0,c,eps);.8333333333e-1
Hazerd
The 0.08333 was when it wasn't executing the loop at all.. so are you sure the maple is right?
Autopulated
+7  A: 
double x0 = 0; /* initial aproximation */
.
.
x1 = x0;
.
.
while (absval(x1-x0) > c1)

at this point, x1 == x0 and c1 is positive, so the loop body is never entered; this is probably not what you intended.

moonshadow