Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 实基和实指数的幂函数_Python_Base_Exp - Fatal编程技术网

Python 实基和实指数的幂函数

Python 实基和实指数的幂函数,python,base,exp,Python,Base,Exp,我需要用Python编写一个幂函数,它可以处理实数基和实数指数 a^b&&a,b∈ R 我被困在这一点上: def power_real_numbers(base, exp): if isinstance(exp, int): return power_bin_recursive(base, exp) else: integer = int(exp) rational = int(str(exp).split('.')[1]) #power_b

我需要用Python编写一个幂函数,它可以处理实数基和实数指数

a^b&&a,b∈ R

我被困在这一点上:

def power_real_numbers(base, exp):

  if isinstance(exp, int):
      return power_bin_recursive(base, exp)
  else:
      integer = int(exp)
      rational = int(str(exp).split('.')[1])

  #power_bin_recursive() works fine
  intval = power_bin_recursive(base, integer)
  ratval = math.sqrt(rational)

  if exp == 0:
       return 1
  elif exp < 0:
       val = intval / ratval
  else:
       val = intval * ratval
  return val

非常感谢您的帮助。

要分割浮点的整数和小数部分,请使用
math.modf

>>> import math
>>> fractional, integer = math.modf(5.5)
>>> fractional
0.5
>>> integer
5.0

您使用了错误的条件来计算实际指数。您的结果适合您的解决方案

正确: 7.5^2.5=154.0469298

您的程序:
7.5^2*sqrt(5)=125.778823734

我想到的问题是“为什么?”不使用
**
运算符可以获得什么样的理解代码中最严重的错误是
2.5
的理性部分是
5
,而
2.500000001
的理性部分是
500000001
,不完全是你所期望的。那么,
**
操作符有什么问题吗?
rational=int(str(exp).split('.')[1])
应该用
rational=int(str(exp).split('.')[0])
使用此处建议的**操作符或数学模块中的pow函数:math.pow(7.5,2.5)
>>> import math
>>> fractional, integer = math.modf(5.5)
>>> fractional
0.5
>>> integer
5.0