Explore the implementation of C + + function pow () • Combination of mathematical and program design (ZZ) __ function

Source: Internet
Author: User
Tags pow

The method of calculating the M-Power of T: (Exploring the implementation of C + + function pow (), combining mathematics with program design)
SOURCE program Download: http://pjy.studio.googlepages.com/powP.cpp
Or to my favorites download.
Because C + + just finished learning function chapter, and practice needs to use POW () This function, so on the special whim, think oneself can write a function that can realize POW () function, after a period of effort, calculate to have some result.
As we all know, pow (double t,double m) is a function of C + + to compute the Y-power of X, although the system provides this POW (), but I still want to write my own pow (). But it may not be easy to write this POW, because the exponential m requirement is double, which can be decimal, and that is not a simple loop to make.
When I first started thinking about this problem, the first idea is to separate the integer and decimal parts of Y, for example, if m=12.34, the x^12.34 into (x^12) * (x^34)/(x^100), so that the case of the index double is converted to three exponents int. The simplest way to get an integer is probably int (y), while the decimal is M-int (m) and then separated by the example. But there may be two problems here:
1.int (y) can cause unexpected results, such as lost data.
2. It is more troublesome to divide a floating point into three parts.
The above two points, plus my estimate that C + + is unlikely to use this method, but should start with the mathematical method, so I find another way. It's also a coincidence that my math analysis class just finished the chapter of power series, and I have the idea of starting with the t^m into a power series, which is just the case in the book:
Introduced by the knowledge of power series when -1<x<1,n-> Infinity (n is an integer), the constant: (1+x) ^m=1+mx+ .... [M* (m-1) *. * (m-n+1) * (x^n)]/(n!) +...
(Specific proof not listed)
And the general term is tmpm, i.e. TMPM (n) =[m* (m-1) *. * (m-n+1) * (x^n)]/(n!)
As a result of -1<x<1, this method can only calculate the 0~2 of the M-power, but if 1+x>=2, then you can turn it to seek 1/(1+x)-M-power can be. In the above, we can find the M-power of the positive T (see t^m as (1+x) ^m). Estimating the POW of C + + may also be implemented in a similar way.

From the formula, first we need to find the x^n, that is, the integer power of a number, this is not difficult:
Double pow_i (double num,int n) to calculate the n power of Num, where n is an integer
{
Double powint=1;
int i;
for (i=1;i<=n;i++) Powint*=num;
return powint;
}
Then, we should also need a function to find n!.
Finally, you can write a function that calculates an expansion:
Double Pow_f (double num,double m) to calculate the M power of NUM, num and M can be double precision, NUM is greater than 0
{
int i,j;
Double powf=0,x,tmpm=1;
X=num-1;
for (i=1;tmpm>1e-12 | | tmpm<-1e-12;i++)//When TMPM is not in the range, stop the loop, the scope can be changed
{
for (j=1,tmpm=1;j<=i;j++)
tmpm*= (m-j+1) *x/j;
POWF+=TMPM;
}
return powf+1;
}
Notice that I did not use pow_i () when I realized the tmpm for each n, nor did I use a function to find n!. Instead, it is written directly into tmpm*= (m-j+1) *x/j, and the TMPM of N is obtained by looping this formula. There is a reason for this:
1. This writing is more concise.
2. If you return n! with a function, the result of a loop will only occur 171 times, because 171! has exceeded the range of double. This can result in poor result accuracy due to insufficient loops, and a possible run-time error.

Here, using Pow_f has been able to find the base is not greater than 2, exponential is the power of the real number. It is easy to think that for the case of the base t>=2, it can be converted to 1/(1+x)-M power. This is theoretically true, but actually the machine shows a problem, that is, when T is compared to the hour (<1), and M is larger, the error is very large, this may be due to insufficient circulation. In other words, this pow_f can not find the t<1,m>1 more accurate value, so the case of the t>2 and the situation will not be able to find, because the conversion of 1/t, and then become the base of less than 1 power problem.
How to solve it, we say, because T is smaller and m larger, in this case, it may be possible to separate m for integers and decimals (respectively, MI,MF), each of the T-Power, and then multiply the two results not on the line, so to T^mi, you can use Pow_i (), T^MF, you can use Pow_f , at this time mf<1, with Pow_f seek T^MF, the result is very accurate. The problem is solved, so the problem of t>=2 is solved.
Finally, there is another problem, is t<0 how to do, here, my processing is, when t<0 is, if the exponent m is an integer, then use Pow_i, and M is not an integer, then return 0 (c + + POW () seems to be handled by mistake, but I am a beginner, did not learn, So let's go back to a 0.

Above all, we also need to have a function as a portal to handle these situations before invoking pow_i and Pow_f:
Double pow_ff (double num,double m)//Calls Pow_f () and pow_i (), calculates the M power of NUM, is the entry of the power
{
if (num==0 && m!=0) return 0;//if num is 0, returns 0
else if (num==0 && m==0) return 1;//if Num and M are both 0, returns 1
else if (num<0 && m-int (m)!=0) return 0;//error, if NUM is negative and M is not an integer number, returns 0
if (NUM&GT;2)//To convert the base greater than 2 to (1/num) ^-m calculation
{
Num=1/num;
M=-m;
}
if (m<0) return 1/pow_ff (NUM,-M);//Turn the index less than 0 to 1/num^-m calculation
if (M-int (m) ==0) return pow_i (NUM,M);/* When the exponent is a floating-point number, it is divided into integers and decimals respectively.
Power, this is because but the base is smaller, with Pow_f directly exponentiation
Error is large, so divided into exponential integer part with pow_i, small
Several parts of the pow_f with the request. * *
else return Pow_f (Num,m-int (m)) *pow_i (Num,int (m));
Return Pow_f (NUM,M);
}

In this way, this pow_ff basically and C + + POW almost, as for the system POW is how to achieve, whether it is done, it is not clear. And this practice makes me feel the combination of mathematics and programming wonderful, ^_^.
Finally, since I was a beginner (studying this, even the array did not learn) so the error is unavoidable, the code may not be, if you have any comments, questions, or better methods, very welcome to tell me AH: pjy.studio@gmail.com

(Special thanks to Baidu know the Blue Crystal, he offered to the M divided into MI and MF advice, then I was in this question for a long time, I was slow to think of this method)

The source code is as follows:

Implement the POW () function of C + + using the functions you write              Making beginners Ba Jun////level Limited, mistakes are unavoidable, welcome to exchange, if you have any comments,///         Please email to: pjy.studio@gmail.com Thank you! #include <iostream> #include <
Cmath> using namespace std; 
Double pow_i (double num,int n);//Calculates the N-power of Num, where n is an integer double Pow_f (double num,double m);//The M-Power of NUM, num and M can be double, num is greater than 0 is less than 2
Double pow_ff (double num,double m);//Call Pow_f () and pow_i () to compute the M-power of NUM, which is the entry of the power;
  int main () {double num,m; 
  cout<< "input base num and exponent m:" <<endl;
  cin>>num>>m;
  cout<< "C + + Answer:" <<pow (num,m) <<endl;
  cout<< "My Answer:" <<pow_ff (num,m) <<endl;
   Double pow_i (double num,int n) to compute the n power of Num, where n is an integer {double powint=1;
   int i;
   for (i=1;i<=n;i++) Powint*=num; ReturnPowint;
    Double Pow_f (double num,double m) to calculate the M power of NUM, num and M can be double precision, NUM is greater than 0 {int i,j;
    Double powf=0,x,tmpm=1;
    X=num-1; 
	            for (i=1;tmpm>1e-12 | | tmpm<-1e-12;i++)///When TMPM is not in the scope, stop the loop, the scope can be changed to {for (j=1,tmpm=1;j<=i;j++)
	            tmpm*= (m-j+1) *x/j;
           POWF+=TMPM;
return powf+1; Double pow_ff (double num,double m)//Calls Pow_f () and pow_i (), calculates the M-power of NUM, is the inlet of the compute power {if (num==0 && m!=0) return 0;//if num is 0, returns 0 else if (num==0 && m==0) return 1;//if Num and M are 0, returns 1 else if (num<0 && m-int (m)!=0) return 0;
		If NUM is negative, and M is not an integer number, then an error, return 0 if (num>2)//to the base is greater than 2 to (1/num) ^-m calculation {num=1/num;
		M=-m; if (m<0) return 1/pow_ff (num,-m), change the exponent less than 0 to 1/num^-m to compute if (M-int (m) ==0) The return pow_i (NUM,M);/* When the exponent is a floating-point number, it is divided into integers and decimal points. 
    Do not seek power, this is because but the base is smaller, with Pow_f direct power error, so divided into the integer part of the index with pow_i, the fractional part of the Pow_f to seek.
    else return Pow_f (Num,m-int (m)) *pow_i (Num,int (m)); Return Pow_f (nUM,M);
 }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.