top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to write your own Pow() function in C?

+5 votes
893 views

I don't want to use any library functions, Interested in How to write your own Pow(X(double),Y(double)) functions in most optimized way... can somebody help me out?

posted Jan 6, 2014 by Atiqur Rahman

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

Not sure what you are looking but power for the floating point is calculated using log and exp operation. See this is what you require -

double Pow(double x, double y) {
    return exp(log(x)*y);
}

Let me know if something different is needed.

answer Jan 6, 2014 by Salil Agrawal
exp(log(x)*y); this much i could do...now things how to calculate exp and log(x)... in most optimized way(but I don't want to use any lib. function not even log and exp)
use

e^{x} = 1 + x + {x^2}{2!} + {x^3}{3!} + ... for all x
log(1-x) = - {x} - {x^2}/2 - {x^3}/3 ...   |x| < 1

Now say you want to calculate 2.5^3.5 break it to (2.5^3)*(2.5^.5) where first part is simple and for second part u need to apply exp and log operations which has power operations but power part is integer...
Nice explanation Salil, I don't think we have any other way...
@Atiqur: Is your problem solved???
In your example, |x| > 1, it is 2.5.  How can we use log(1-x) equation?
Thanks
I think you have missed one point say you want to calculate 2.5^3.5 break it to (2.5^3)*(2.5^.5) now first part is easy we just need the 2.5^.5 where x = .5

I hope this should clear your doubt.
Similar Questions
+1 vote

Write your own rand function which returns random numbers in a given range(input) so that the numbers in the given range is equally likely to appear.

0 votes
#include <stdio.h>
#include<math.h>
int main()
{

  printf("%.0f",pow(2,1023));

  return 0;
}

Output: 89884656743115795386465259539451236680898848947115328636715040578866337902750481566354238661203768010560056939935696678829394884407208311246423715319737062188883946712432742638151109800623047059726541476042502884419075341171231440736956555270413618581675255342293149119973622969239858152417678164812112068608

Now question is how is it achieved for such a big number?

Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...