# Mathematical Error

• 11-25-2006
toonlover
Mathematical Error
Hello you guys! I don't know why my compiler is giving me this error:
Code:

```code.cpp(23) : error C2296: '^' : illegal, left operand has type 'float' code.cpp(26) : error C2296: '^' : illegal, left operand has type 'float'```
And here is the place where I get the error:
Code:

```float Height(float G,float V, float S,int POSNEG) {       if(POSNEG == POSITIVE)       {return(((-2*V)/(2*G)) + sqrt((-2*S)/(G)) + ((2*V^2)/(4*G))*2*G);}       if(POSNEG == NEGATIVE)       {return(((-2*V)/(2*G)) - sqrt((-2*S)/(G)) + ((2*V^2)/(4*G))*2*G);}       else       {             return ERROR;       } }```
• 11-25-2006
The Brain
you are using ^ as an exponentential operation.. when in actuality, it is a bitwise operation using the XOR bitwise operator. common mistake, but easy to fix. try using the pow( ) function from <cmath>
• 11-25-2006
toonlover
So how exactly do I implement that function in this case??
• 11-25-2006
The Brain
Code:

`((2*V^2)/(4*G))*2*G);`

could be written as:
Code:

`((pow(2*V, 2)/(4*G))*2*G);`
• 11-25-2006
toonlover
thanx!!
• 11-25-2006
robatino
Actually, that would be 2*pow(V, 2), assuming that what's meant is 2*(V^2) and not (2*V)^2. In this case it would be easier and more efficient to just write it as 2*V*V.

Edit: And in the second case, 4*V*V.
• 11-25-2006
grumpy
Quote:

Originally Posted by robatino
Actually, that would be 2*pow(V, 2), assuming that what's meant is 2*(V^2) and not (2*V)^2.

Indeed. exponentiation has a higher precedence mathematically than multiplication. So (for ^ being exponentiation and * being multiplication) any mathematician would read 2*v^2 as 2*(v^2) rather than as (2*v)^2.

Quote:

Originally Posted by robatino
In this case it would be easier and more efficient to just write it as 2*V*V.

Indeed. This is one of the simple common tricks used in numerical code. Exponentiation is often markedly less efficient (in terms of machine clock cycles, and therefore runtime speed) than multiplication --- and a compiler has more chance of optimising 2*v*v than it does of optimising 2*pow(v, 2.0).

I would also do some basic algebra (elimination of common terms, precedence of operations) to turn this;
Code:

`return (((-2*V)/(2*G)) + sqrt((-2*S)/(G)) + ((2*V*V)/(4*G))*2*G);`
into
Code:

`  return (sqrt(-2*S/G) + V*V - V/G );`