#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2017
    Posts
    14
    Rep Power
    0

    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;
    }
  2. #2
  3. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,861
    Rep Power
    509

    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!

IMN logo majestic logo threadwatch logo seochat tools logo