0

I need to write a power function in Python which works with real base and real exponent.

a^b && a,b ∈ R

I'm stuck at this point:

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

This only works with real base though. With real exp the numbers differ, for example:

7.5 ^ 2.5 = 154.046969298, output by power_real_numbers is 125.778823734
7.5 ^ 0.5 = 2.73861278753, output by power_real_numbers is 2.2360679775
7.5 ^ -2.5 = 0.00649152660747, output by power_real_numbers is 0.00795046392

Any help is appreciated.

ZdaR
  • 22,343
  • 7
  • 66
  • 87
  • 1
    The question that comes to mind is "why?" What kind of understanding is gained by not using `**` operator – Antti Haapala -- Слава Україні Mar 08 '15 at 13:02
  • the worst bug in your code is that the rational part for `2.5` is `5` and the rational part for `2.500000001` is `500000001`, not quite what you'd expect. – Antti Haapala -- Слава Україні Mar 08 '15 at 13:07
  • So, what's wrong with the `**` operator? – Klaus D. Mar 08 '15 at 13:08
  • `rational = int(str(exp).split('.')[1])` this should be replaced by `rational = int(str(exp).split('.')[0])` – ZdaR Mar 08 '15 at 13:09
  • Use either the ** operator as suggested here or the pow function from math module: math.pow(7.5, 2.5) – smichak Mar 08 '15 at 13:09
  • I cannot use the ** operator as this is a form of a school task. Thanks for that math.modf function, yet there is something terribly wrong with my algorithm anyways. I was trying to write that function according to the advice given in this topic https://stackoverflow.com/questions/2882706/how-can-i-write-a-power-function-myself/2882819#2882819?newreg=a435f0a702224ded8a1831230a17e837 but i guess i failed. – TheRetardedOne Mar 08 '15 at 13:32

2 Answers2

0

For splitting the integer and fractional part of a float, use math.modf:

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

You are using wrong conditions to calculate real exponent. Your results are okay for your solution.

True: 7.5 ^ 2.5 = 154.046969298

Your program: 7.5 ^ 2 * sqrt(5) = 125.778823734

Martin Bokša
  • 188
  • 1
  • 1
  • 11