# usage of powl() function - C programming

Discussion in 'Mac Programming' started by tom1992, Sep 30, 2010.

1. ### tom1992 macrumors newbie

Joined:
Aug 26, 2010
#1
Hi, this is probably a very simple problem however I cannot get a valid output from the powl() function. everytime I run it, it gives an output of 0.00. This is probably just a simple usage problem but I can't work out how to raise long double variables to the power of other long double variables. My program is an iterative calculation of pi using 4*(4arctan(1/5)-arctan(1/239). I know you could use the inbuilt arctan functions in math.h but i wanted to make it iterative. I have read the man pages on pow()/powf()/powl() and scoured google but can't get it to work.

sorry for if i'm being thick.

Code:
```/*
program works by working out pi as 4*(4arctan(1/5)-arctan(1/239)
it approximates arctan(z) as (z^1)/1-(z^3)/3+(z^5)/5-...
*/

#include <stdio.h>
#include <stdbool.h>
#include <math.h>

int main (int argc, const char * argv[]) {
long double pi, arctan1, arctan2, divisor;
bool sign;
int count;
sign = 0;
count = 0;
divisor = 1;
printf("\n");
while (count < 100) {

if (sign == 0)

{
arctan1 += (( powl( (1/5) , divisor))/divisor );
arctan2 += (( powl ( (1/239) , divisor))/divisor );
sign = 1;

}

else

{
arctan1 -= (( powl ( (1/5) , divisor))/divisor );
arctan2 -= (( powl ( (1/239) , divisor))/divisor );
sign = 0;

}

pi=4*((4*arctan1)-arctan2);

printf("\r%.050Lf", pi);
count++;
divisor +=2;

}

return 0;

}
```

2. ### ianray macrumors 6502

Joined:
Jun 22, 2010
Location:
@
#2
Two things:
1. arctan1 and arctan2 are not initialized
2. 1/5 and 1/239 are an integer expressions -- change to 1/5. (or 1/5.0 if you prefer) to force floating point

Good luck

3. ### tom1992 thread starter macrumors newbie

Joined:
Aug 26, 2010
#3
thanks. I got it working now

Code:
```/*
program works by working out pi as 4*(4arctan(1/5)-arctan(1/239)
it approximates arctan(z) as (z^1)/1-(z^3)/3+(z^5)/5-...
*/

#include <stdio.h>
#include <stdbool.h>
#include <math.h>

int main (int argc, const char * argv[]) {
long double pi, arctan1, arctan2, divisor, a, b;
bool sign;
int count;
a = (1.0)/(5.0);
b = (1.0)/(239.0);
sign = 0;
count = 0;
divisor = 1;
printf("\n");
while (count < 20) {

if (sign == 0)

{
arctan1 += (( powl ( a , divisor))/divisor );
arctan2 += (( powl ( b , divisor))/divisor );
sign = 1;

}

else

{
arctan1 -= (( powl ( a , divisor))/divisor );
arctan2 -= (( powl ( b , divisor))/divisor );
sign = 0;

}

pi=4*((4*arctan1)-arctan2);

printf("\r%.061Lf", pi);
count++;
divisor +=2;

}
printf("\n");
return 0;

}
```
it also requires many less iterations than I expected!

4. ### ianray macrumors 6502

Joined:
Jun 22, 2010
Location:
@
#4
Great! Note that arctan1 and arctan2 are not initialized to zero, so your program will fail if the stack contains non-zero values.