x^x=2016 (bisection)

Can someone tell me where the error is? When I run it, I see just a blinking underscore.

Sorry if the mistake is obvious!

Thank you :-)

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
#include <iostream>
#include <math.h>

using namespace std;

float a, b, x, y;
float eps=1e-10;

int main()

{
    a=1;
    b=8;

    while((b-a)>eps){

    x=(a+b)/2;
    y=exp(x*log(x));

        if (y<2016)
            a=x;
        else
            b=x;
    }

    cout << x << endl;

    return 0;
}
The debugger is your best friend for situations like this. I placed on the comments the values for the first three iterations of the while loop. Your while loop is an infinite loop. You could place a cout after each statement to see the values as it loops thru it.

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
#include <iostream>
#include <math.h>

using namespace std;

float a, b, x, y;
float eps = 1e-10;

int main()

{
    a = 1;
    b = 8;

    while ((b - a)>eps){

	   x = (a + b) / 2; //(1 iteration)4.50 ; (2 iteration)6.25 ; (3 iteration)5.375
	   y = exp(x*log(x)); //(1)869.874268 ; (2)94243.2266 ; (3)8429.15332

	   if (y<2016) // (1)True (869.87 < 2016) ; (2)go to Else ; (3)go to Else
		  a = x; // (1)a= 4.50
	   else
		  b = x; // (2) 6.25 ; (3) 5.375
    }

    cout << x << endl;

    return 0;
}
Thank you. You're right.

I can't figure out why, though. When I run it with
cout << x << endl;

still in the loop, it ends up with 4.83092 being the output result over and over, which is the correct answer. It's strange, because it seems like the difference between a and b should be smaller that the epsilon by that point, right?

I'm sorry for being so clueless, but I really don't know how to solve this issue.
Instead of outputting only x, try
 
cout << "a: " << a << "\tb: " << b << "\t(b-a): " << (b-a) << "\teps: " << eps << endl;
inside the loop. I am guessing you are using the (32bit) MSVC compiler, you will find that 1e-10 is never reached. This is because the float has insufficient accuracy, have a look here: [url]https://msdn.microsoft.com/en-us/library/s3f49ktz.aspx[/url]

I first compiled your code with a 64bit GCC compiler and terminated fine.
If you use the (32-bit)MSVC compiler your code will also terminate properly after you change the floats to doubles.

So the problem is not in your code, it is in the accuracy of the execution.
Thank you! You're right about the compiler.

I felt like this might be the case, but I didn't know how to deal with it.

Thank you again! :-)
Topic archived. No new replies allowed.