Why am I not getting the correct result when calculating the exponent using ^ in C ++?
I am using Bode formuala to calculate the distance of the nth planet from the sun
dist = (4 + 3*(2^(n-2)))/10
If I calculate the distance this way, I get the correct 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 wrong values:
vector <double> dist(5);
for (unsigned int i = 2; i < 5; i++)
{
dist[i] = ((4 + 3*(2^(3-2)))/10.0) ;
}
Why is that?
a source to share
The symbol ^
is a bitwise exclusive or, not the exponential function you would expect.
Since you are calculating this in a loop already, you can easily generate the 2 powers you need in the equation, something as 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 case, we'll initialize the j
first value n-2
you want, then proceed to multiply it by 2 to get the next cardinality of 2 you need.
a source to share
First, there ^ stands for "xor", not "force". For the other, you compute a constant value (you did 3-2
instead i-2
). However, since you need a power of two, bit shifting might work. ("1 <X" works like "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).
a source to share
Operator ^
in C ++ (and several other languages) means "exclusive" or " not " for more power.
C ++ does not have a "raise force" operator; you need to use a 2-argument function pow
(you can #include
old C-generation <math.h>
or #include <cmath>
and use std::pow
) that returns double
; or as other answers suggested, for this special case you can use bit shift.
a source to share