Python implementation principle of math library (pow(a, x) operation)

Python implementation principle of math library (pow(a, x) operation)

First of all, it is stated that this is not necessarily the actual underlying function. It is just written according to the formula by consulting the information. For the exponential function, only Taylor expansion is used for the time being. If there are other methods, please provide the principle or formula. The principle of the algorithm is relatively simple, that is, Taylor expansion. Need to be used insideIt has been provided in the above article. In fact, it is also Taylor expansion, but the situation is more complicated than this, but the source code of the dependent function will still be provided below. The purpose of this series is to use basic arithmetic symbols, +-*/% to implement the math library % Is not a basic operation, but it is too simple and basic to write a separate formula. The formula is as follows, but for integer multiples, it is found that the number of convergence is more difficult than decimals, so generally integers and decimals are calculated separately.

[python]



  • Epsilon = 10e-16
  • def fab_h(x):
  • '''''
  • Find the absolute value of a real number
  • :param x: R
  • '''
  • if x >= 0:
  • return x
  • else:
  • return x * -1
  • def ln_h(x):
  • '''''
  • ln function expansion
  • :param x: 0<x
  • :return:ln(x)
  • '''
  • ln10 = 2.30258509299404568401
  • def ln_h1(x):
  • s2 = 0.0
  • delta = x = (x-1.0)/(x + 1.0)
  • i = 0
  • while fab_h(delta * 2)/(i * 2 + 1)> Epsilon:
  • s2 += delta/(i * 2 + 1)
  • delta *= x * x
  • i += 1
  • return 2 * s2
  • coef = 0
  • if x> 10:
  • while x/10> 1:
  • coef += 1
  • x/= 10
  • return ln_h1(x) + coef*ln10
  • elif x <1:
  • while x * 10 <10:
  • coef += 1
  • x *= 10
  • return ln_h1(x)-coef*ln10
  • else:
  • return ln_h1(x)
  • def fac_h(x):
  • '''''
  • Factorial function
  • x int and x>=1
  • '''
  • result = 1
  • while x> 1:
  • result *= x
  • x -= 1
  • return result
  • def pow_h(a,x):
  • '''''
  • Exponential function
  • :param a: base R
  • :param x: index R
  • '''
  • result = 1.0
  • coef_fac = 1.0
  • if x% 1 == 0:
  • '''''Integer multiples'''
  • while coef_fac <= x:
  • result *= a
  • coef_fac += 1
  • return result
  • exp = exp_orgin = x*ln_h(a)
  • '''''Decimal multiples'''
  • while fab_h(result-exp/fac_h(coef_fac))> Epsilon:
  • result += exp/fac_h(coef_fac)
  • exp *= exp_orgin
  • coef_fac += 1
  • return result

For more free technical information, please pay attention to: annalin1203