0

I want to write a function computing pow(x,n). However when input (x=2.00000, n=-2147483648), The first code will "numerical out of range". The second paragraph code performs normally.

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n>=0:
            return self.powpositive(x,n)
        else:
            return 1/self.powpositive(x,-n)
        
    def powpositive(self,x,n):
        if n==0:
            return 1
        else:
            if n%2==0:
                return pow(self.powpositive(x,n//2),2)
            else:
                return x*pow(self.powpositive(x,(n-1)//2),2)
OverflowError: (34, 'Numerical result out of range')
  [Previous line repeated 19 more times]
    return pow(self.powpositive(x,n//2),2)
Line 15 in powpositive (Solution.py)
    return pow(self.powpositive(x,n//2),2)
Line 15 in powpositive (Solution.py)
    return pow(self.powpositive(x,n//2),2)
Line 15 in powpositive (Solution.py)
    return 1/self.powpositive(x,-n)
Line 6 in myPow (Solution.py)
    ret = Solution().myPow(param_1, param_2)
Line 46 in _driver (Solution.py)
    _driver()
Line 57 in <module> (Solution.py)
class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n>=0:
            return self.powpositive(x,n)
        else:
            return 1/self.powpositive(x,-n)
        
    def powpositive(self,x,n):
        if n==0:
            return 1
        elif n==1:
            return x
        else:
            ret=self.powpositive(x,n//2)
            if n%2==0:
                return ret*ret
            else:
                return x*ret*ret

I don't see the difference between the two codes, what's happening?

Mark
  • 7,785
  • 2
  • 14
  • 34
Jxb
  • 1
  • 3
  • Do you understand what the error means? (If not, then this is a duplicate.) Did you try to check what values of `x` and `n` are passed to the function? Do you understand what range of values is allowed for a floating-point number? Did you try to check what happens, step by step, as each version of the code runs? Where exactly did it run into a problem? What is your remaining question, after doing that much debugging and research? – Karl Knechtel Aug 19 '23 at 15:19
  • Hint: what happens if you set `x = 2.0 ** 1000`, and then attempt `x * x` and `x ** 2` and `pow(x, 2)`? (I'm casting the last vote to close anyway, because if you actually attempt the expected debugging work, the underlying issue is that one, which is already addressed perfectly well by the duplicate.) – Karl Knechtel Aug 19 '23 at 15:25

0 Answers0