Problem of the Day
A new programming or logic puzzle every Mon-Fri

Is Negative

The premise of this problem sounds easy. Write a function that returns if a number is negative or not. The tricky part comes from detecting -0. Your experience may vary be language. You'll also note that IEEE says that -0 === +0. Make sure your function can tell the difference.

Permalink: http://problemotd.com/problem/is-negative/

Comments:

  • Jason - 9 years, 10 months ago

    // JavaScript uses the IEEE 754 standard, so 1/-0 = -Infinity
    function isNegative0(x) {
      return x === 0 && (1/x) === -Infinity;
    }
    
    console.log("+0:",isNegative0(+0)); // false
    console.log("-0:",isNegative0(-0)); // true
    

    reply permalink

  • Jason - 9 years, 10 months ago

    Wow... I should read the whole problem.... here is the correct one

    // JavaScript uses the IEEE 754 standard, so 1/-0 = -Infinity
    function isNegative(x) {
      return x < 0 || (x === 0 && (1/x) === -Infinity);
    }
    
    console.log("+1:",isNegative(+1)); // false
    console.log("+0:",isNegative(+0)); // false
    console.log("-0:",isNegative(-0)); // true
    console.log("-1:",isNegative(-1)); // true
    

    reply permalink

  • Jason - 9 years, 10 months ago

    main :: IO ()
    main = do
        print $ isNegative (1 :: Double) -- False
        print $ isNegative (0 :: Double) -- False
        print $ isNegative (-0 :: Double) -- True
        print $ isNegative (-1 :: Double) -- True
    
    isNegative :: RealFloat a => a -> Bool
    isNegative x
        | x < 0 = True
        | isNegativeZero x = True -- Haskell has isNegativeZero defined for RealFloat in Prelude
        | otherwise = False
    

    reply permalink

Content curated by @MaxBurstein