#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    4
    Rep Power
    0

    Why doesn't the '**' operator return a positive value


    Hi everybody

    I have recently started learning python from C++ and its been great! However I ran into a bug which was a bit annoying but I soon found out what it was. When I was using comparative operators for conditional statements, I realised that the '**' operator returns a negative value when I write an equation like this [negative number]**2. I don't understand this because surely it would return a postive number as it is doing say -5 * -5 which would return 25? Is there any other way to make multiply a base to the power of x to make it return a positive value in the given circumstance? Thank you!
  2. #2
  3. Banned ;)
    Devshed Supreme Being (6500+ posts)

    Join Date
    Nov 2001
    Location
    Woodland Hills, Los Angeles County, California, USA
    Posts
    9,625
    Rep Power
    4247
    It has to do with python's operator precedence.
    x = (-5) ** 2 sets x to 25
    x = -5 ** 2 sets x to -25

    This is because, without the parenthesis, it will evaluate 5 ** 2 first and then put the - sign on the result and hence you get -25.
    Up the Irons
    What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
    "Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
    Down with Sharon Osbourne

    "I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website." - Nilpo
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Jun 2013
    Posts
    4
    Rep Power
    0
    Originally Posted by Scorpions4ever
    It has to do with python's operator precedence.
    x = (-5) ** 2 sets x to 25
    x = -5 ** 2 sets x to -25

    This is because, without the parenthesis, it will evaluate 5 ** 2 first and then put the - sign on the result and hence you get -25.
    Thank you, this makes sense now!
  6. #4
  7. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    610
    Rep Power
    65
    This works too ...
    Code:
    a = -5
    x = a**2
    print(x)  # 25
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25

IMN logo majestic logo threadwatch logo seochat tools logo