Calculating ATan and ATan2

Hi, I am trying to use these formulas to calculate ATan2 using this formula:
http://upload.wikimedia.org/math/3/0/a/30a3f547e111a829771a8 3bcbcb517a4.png
Which requires ATan, so I am using this formula:
http://upload.wikimedia.org/math/d/f/b/dfbc0d6f528500cae08e8 417add2e0da.png

I have this code for ATan and I want to know if there is a much more efficient way to do it with the sizes of the numbers I am working with.

typedef ttmath::Big<TTMATH_BITS(8192), TTMATH_BITS(8192)> BigFloat;

BigFloat ATanBF(BigFloat z, const unsigned long &p = 128)
{
BigFloat t;
BigFloat _ (0.0);
for(unsigned long i = 1; i < p; ++i)
{
_.FromDouble(0.0);
t = z;
t.Pow(_ += double(i * 2 + 1));
t.Div(_ += double(i * 2 + 1));
if(i % 2 == 0)
{
z += t;
}
else
{
z -= t;
}
}
return(z);
}

Currently it is very inefficient because I am not very familiar with the library. I know that some of it it because the numbers are quite large, but is there a way to make my code more efficient? I feel like I am doing something wrong.

Added by: tomek, 2011 VII 14, Last modified: 2011 VII 14

You can a little optimize it by having a numerator remembered in a variable and then instead of powering just use multiplication.

But you must know that the expression for ArcTan is valid only when the argument is close to zero. And if you are using only 128 iterations your result is a very bad approximation. Calculating ATanBF(0.3) gives 0.295712081... so the error is in the third digit consequently there is no sense to use Big<TTMATH_BITS(8192), TTMATH_BITS(8192)>. You can perform calculations on Big<1, 1> and at the end cast it to a greater type.

Additionaly you probably do not need such large exponent, try: typedef ttmath::Big<1, TTMATH_BITS(8192)> BigFloat; may this will be sufficient.

TTMath has a better (much accurate but slower) ArcTan function:

int main()
{
BigFloat a = "0.3";
std::cout << ttmath::ATan(a) << std::endl;
}

Above ttmath::ATan() at the end uses the same expression as your version, you can see it here: ATan0. Copy and paste it to your code and set how many iterations you need.

Added by: ~LB, 2011 VII 14

Thank you, I'll get working on that. And you are right I did not need that large of a number - I'm not sure what I was thinking. Knowing there is an ATan function already in the library is great - this will make things easier for me. Thanks!