math库的Python实现原理(pow(a, x)运算)

687 阅读1分钟

首先声明这并不一定是实际的底层函数,只是查阅资料根据公式写的,对于指数函数暂时只使用了泰勒展开,若有其他方法欢迎提供原理或公式,该算法原理比较简单,就是泰勒展开,里面需要利用的在上面的文章中已经提供了,其实也是泰勒展开但情况比这个复杂点,不过下面依旧会提供依赖函数的源码,该系列的目的就是利用基本运算符号,+-*/%进行math库的实现,%不算基本运算,但是太简单和基本就不写单独的了,公式如下,但是对于整数倍发现收敛次数比小数更困难,所以一般整数和小数都是分开算的。

[python]



  • Epsilon = 10e-16
  • def fab_h(x):
  • '''''
  • 求实数的绝对值
  • :param x: R
  • '''
  • if x >= 0:
  • return x
  • else:
  • return x * -1
  • def ln_h(x):
  • '''''
  • ln函数泰勒换元展开
  • :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):
  • '''''
  • 阶乘函数
  • x int and x>=1
  • '''
  • result = 1
  • while x > 1:
  • result *= x
  • x -= 1
  • return result
  • def pow_h(a,x):
  • '''''
  • 指数函数
  • :param a: 底数 R
  • :param x: 指数 R
  • '''
  • result = 1.0
  • coef_fac = 1.0
  • if x % 1 == 0:
  • '''''整数倍'''
  • while coef_fac <= x:
  • result *= a
  • coef_fac += 1
  • return result
  • exp = exp_orgin = x*ln_h(a)
  • '''''小数倍'''
  • while fab_h(result - exp/fac_h(coef_fac)) > Epsilon:
  • result += exp/fac_h(coef_fac)
  • exp *= exp_orgin
  • coef_fac += 1
  • return result

更多免费技术资料可关注:annalin1203