tags:

views:

148

answers:

5

I am using Bode's formuala to calculate distance of nth planet from sun

dist = (4 + 3*(2^(n-2)))/10

If I calculate the distance this way, I get the right values:

dist[2] = ((4 + 3*1)/10.0) ;  
dist[3] = ((4 + 3*2)/10.0) ;  
dist[4] = ((4 + 3*4)/10.0) ;

But doing it this way, gives me incorrect values:

vector <double> dist(5);  

for (unsigned int i = 2; i < 5; i++)  
{  
    dist[i] = ((4 + 3*(2^(3-2)))/10.0) ;  
}

Why so?

+8  A: 

The ^ character represents a bitwise exclusive or, not the exponential function that you expect.

Since you're calculating this in a loop already you can easily generate the powers of 2 that you need in the equation, something simple (and close to your code) would be:

vector<double> dist(5);
unsigned int j = 1;
for(unsigned int i = 2; i < 5; i++){
    dist[i] = (4+3*j)/10.0;
    j = j * 2;
}

In this particular instance, we initialize j to the first value of n-2 that you require, then proceed to multiply it by 2 to get the next power of 2 that you require.

Mark E
Thanks man...Silly mistakes everytime.
xbonez
+7  A: 

Because ^ is not the power operator in C++. You can use std::pow but with double or you can do a lot of casting to make it work with int.

AraK
+1  A: 

The ^ operator, in C++ (and several other languages) means "exclusive or", not "raise to power".

C++ does not have a "raise to power" operator; you need to use the 2-argument function pow (you can #include the old C-generation <math.h>, or #include <cmath> and use std::pow), which returns a double; or, as other answers have suggested, for this special case you might use bit-shifting.

Alex Martelli
+5  A: 

First off:

dist[i] = ((4 + 3*(2^(3-2)))/10.0) ;

Is constant. I believe you meant to do the following:

dist[i] = ((4 + 3*(pow(2, (i-2)))/10.0) ;
Raul Agrait
+2  A: 

For one, there's ^ means "xor", not "power of". For another, you're calculating a constant value (You did 3-2 instead of i-2). However, since you want a power of two, bit-shifting can work your way. ("1 << X" works out as "2^X")

vector <double> dist(5);

for (unsigned int i = 2; i < 5; i++) {
   dist[i] = ((4 + 3*(1 << (i - 2)))/10.0) ;
}

For other bases, you need the pow() library function found in <math.h>/<cmath> (C/C++, respectively).

Kyte
"For other bases, you need the pow()" ...that's simply not true.
Mark E
Well, assuming you don't pull off the exponentiation yourself through iteration, yes. Oversight of mine.
Kyte