September 18th, 2017, 05:19 AM
-
How to add Power of x variable in C?
Hi,
How to replace below codes with power of x?
Code:
int main()
{
float x=0.5;
float tanh;
tanh=x-(x*x*x/3)+2*(x*x*x*x*x/15)-17*(x*x*x*x*x*x*x/315); // How to replace with power
printf("%f",tanh);
return 0;
}
September 18th, 2017, 10:46 AM
-
3 alternatives presented
Investigate the function in the c standard library (google it). To build this program you'll need to link with the math library. On unix I compiled with command
$ # source file is c.c
$ make LOADLIBES=-lm CFLAGS=-Wall ./c
Code:
#include<math.h>
#include<stdio.h>
int main()
{
float x=0.5;
float TANH, xx;
TANH=x-(x*x*x/3)+2*(x*x*x*x*x/15)-17*(x*x*x*x*x*x*x/315); // How to replace with power
printf("%f\toriginal\n",TANH);
xx = x*x;
printf("%f\tfactored\n",x*(1+xx*(-1/3.0f+xx*(2/15.0f+xx*(-17/315.0f)))));
printf("%f\tpow function\n",x-powf(x,3)/3+2*powf(x,5)/15-17*powf(x,7)/315);
printf("%f\ttanh function\n",tanhf(x));
return 0;
}
For performance considerations, I'd bet that tanh is fastest, followed by the "factored" variant, next with the pow function, and finally your version is slowest. But don't feel badly, your version gets the expected answer and that's primary.
[code]
Code tags[/code] are essential for python code and Makefiles!