tags:

views:

109

answers:

3

Hi guys!

I have a little problem in my code. The variables don't want to change their values. Can you say why? Here is my code:

vector<coordinate> rocks(N);
double angle;
double x, y;
// other code
while (x > 1.0 || x < -1.0 || y > 1.0 || y < -1.0) {
    angle = rand() * 2.0 * M_PI;
    cout << angle << endl;
    cout << rocks[i - 1].x << endl;
    cout << rocks[i - 1].y << endl;
    x = rocks[i-1].x + r0 * cos(angle);
    y = rocks[i-1].y + r0 * sin(angle);
    cout << x << endl;
    cout << y << endl << endl;
}
// other code

And the result on the console is:
6.65627e+09
0.99347
0.984713
1.09347
0.984713

1.16964e+09
0.99347
0.984713
1.09347
0.984713

As you see the values of x, y variables doesn't change and this while be an infinity loop. What's the problem? What do you think?

+12  A: 

Why are you expeciting x and y to change? You assign to them the value of a calculation that doesn't change?

rand() * 2.0 * M_PI is always a multiple of 2 * pi (as far as a double can represent) so cos(angle) will be 1 and sin(angle) will be 0.

Charles Bailey
I think this will be the good answer... :P I'll check it ;)
Infinity
Yes. The C standard rand function returns ints, not doubles.
A. Levy
+1 on this one. Basically, I think the original user is expecting rand() to return between 0 and 1 floating point, not 0 to RAND_MAX as is stated here: http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
Kevin
Yes, you are right... :D thanks!!!
Infinity
Yes, the `int` returned by `rand()` will be promoted to a `double` when multiplied by `2.0`.
Charles Bailey
Changing that to `(rand() * 2.0) / RAND_MAX * M_PI` will get you an angle between 0 and 2 * M_PI.
David Thornley
And don't forget to call `srand()` first.
Potatoswatter
There are assignments to both x and y. The problem (with those not changing) is also that `i` isn't changing.
dash-tom-bang
A: 

Perhaps your rand() function isn't defined. Sometimes failing to include the correct headers results in an odd default rand being called, and it may always return the same number. This is just off the top of my head, but I would check in that direction.

Actually, I don't ever remember this happening with rand, but I think I've seen it happen with the trigonometric functions if you don't include math.h. Though that may be a compiler specific quirk.

A. Levy
A: 

angle you are generating seems to be extremely large. I'm assuming you want to generate angle between 0 and 2*pi. Check to see if rand() is returning a number between 0 to 1 and also check to see what M_PI is.

If that doesn't help, find out what each elements are by adding more cout

sjchoi