PDA

View Full Version : usage of powl() function - C programming




tom1992
Sep 30, 2010, 05:12 AM
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.



/*
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;

}



ianray
Sep 30, 2010, 06:01 AM
Two things:

arctan1 and arctan2 are not initialized
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 :)

tom1992
Sep 30, 2010, 06:10 AM
thanks. I got it working now


/*
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!

ianray
Sep 30, 2010, 08:32 AM
Great! Note that arctan1 and arctan2 are not initialized to zero, so your program will fail if the stack contains non-zero values.