Why wont this square root properly?

a=((s1.rel)*(s2.rel))-((s1.img)*(s2.img));
b=((s1.rel)*(s2.img))+((s2.rel)*(s1.img));
c=((sqrt(a * a) + (b * b)));
d=((atan (b/a)*((57.2958))));
cout<<"nMultiplication: "<<"("<<c<<")"<<"+"<<"("<<d<<")"<<"i";
Define "properly".

You have quite a lot of parentheses. Are they all necessary?

Your equation for 'c' is equivalent to c = abs(a) + b*b;. Is that intentional?
i need c to equal the square root of a squared + b squared but when i run the program it gives me the wrong value?
In terms of the parentheses the are all necessary.
Not sure what it is that you're trying to compute but it looks similar do a distance calculation.


   |\
 a | \ c
   |  \
   |___\
     b
     _______
c = √a² + b²


If that's the case you need to move the addition of b*b inside the parentheses of the square root call. I honsestly think you're using way too many parentheses here. You're probably confusing yourself.

1
2
// Is this what you want?
c = sqrt(a * a + b * b);
I'd definitely get rid of the excess parentheses - they serve to obscure what is going on - thus increasing the likelihood of accidental mistakes.

Order of precedence of the various operators takes care of the order in which things are done here.

1
2
3
4
5
a = s1.rel*s2.rel - s1.img*s2.img;
b = s1.rel*s2.img + s2.rel*s1.img;

c = sqrt(a*a + b*b);
d = atan(b/a) * 57.2958;


See Precedence of operators
http://www.cplusplus.com/doc/tutorial/operators/
Last edited on
thank you all for your help, solved now! and ive removed the parentheses hahaa
If you are going to do it this way you should use atan2(y,x) rather than atan(x): you will get an answer in the correct quadrant (otherwise you will be wrong 50% of the time) and you won't crash when a = 0.

Given what you are doing you would be better with complex numbers: see the advice given to you in your other post.

What you have written in your answer line is also patently wrong: that is not a polar form. You want something like, e.g.,
cout << "Multiplication: " << c << " exp( " << d << " i)" << endl;
or, if you must,
cout << "Multiplication: (modulus, argument) = (" << c << ", " << d << " )" << endl;

For complex numbers in polar form leave the angle in radians - there is no need for the extra multiplying factor of 57.2958, which would be incorrect once it is inside the complex exp().
Last edited on
Registered users can post here. Sign in or register to post.