Tuesday, 21 May 2013

FIND FRACTIONAL POWER OF A NUMBER WITHOUT USING ANY PREDEFINED FUNCTION IN C

For a very good and very efficient program you must visit my updated post here. Believe me, It's really a wonderful post.

Here is a mind-blowing program to find the fractional power of any number (no matter whether it is float or integer) without using any predefined function in C, or not including any header file that contains functions to perform this task.
Although my code is not that efficient as the predefined pow() function in math.h header file, as for very large values it may give some deviations from the actual result, but here my aim is to illustrate the algorithm that I have designed to do this simple looking task. Friends, believe me, it was very difficult to think and implement the concept for finding the fractional power. In the starting we may think that it's an easy task because most of us can easily find the integral powers of any number, simply through a for loop with an integer loop counter, but when it comes to fractional power, it becomes a bit complex. 



Source code:-
/********************************************************************************/

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

long double roundoff(long double);
long double power(long double,long double);
long double cal(long double num,long double p)
{
long double i,answer,counter=1,z=0.0000001,ans;
for(i=0;i<num;i=i+z)
{
if((power(i,power(10,counter))) > num)
{
i=i-z;
break;
}
}
p=(p*power(10,counter));
p=roundoff(p);
answer=power(i,p);
return answer;
}

long double roundoff(long double num)
{
long double limit;
limit=(int)num+0.5;
if(num>limit)
return ((int)num + 1 );
else
return ((int)num);
}

long double power(long double num,long double i)
{

long double j;
long double product=1;

for(j=0;j<i;j++)
{
product*=num;
}
return product;
}


int main()
{
long double num,p,a,b,pi,pf,answer;
clrscr();
printf("ENTER ANY NUMBER : ");
scanf("%Lf",&num);

printf("ENTER THE POWER : ");
scanf("%Lf",&p);
pi=(int)p;
pf=p-pi;

a=cal(num,pf);
b=power(num,pi);

answer=a*b;

printf("\n\nmy answer= %Lf\n"
"correct answer = %f",answer,pow((double)num,(double)p));
getch();
return 1;
}
/*******************************************************************************/

Some sample outputs:-




Here are some situations where my code proves to be a better one as compared to the pow() function.
Clearly in the following two examples the inbuilt power function gives wrong answer, but my code gives the correct answer, you can check using calculator.



I'm looking forward for readers suggestions to improve my code, and any other algorithm so that I can have another algorithm for this question.

1 comment:

  1. Can you explain the math behind the function cal(). How did you arrive at it

    ReplyDelete