22

Is there a simple math function available that compares numbers x and y and returns -1 when x is less than y, 1 when x is more than y and 0 when they're equal?

If not, would there be a elegant solution (without any if's) to convert the output of Math.Max(x, y) to these returns? I was thinking of dividing the numbers by themselves, e.g. 123/123 = 1 but that will introduce the problem of dividing by 0.

0

8 Answers 8

35

For your strict -1, 0 or 1 requirement, there's no single method that is guaranteed to do this. However, you can use a combination of Int32.CompareTo and Math.Sign:

int value = Math.Sign(x.CompareTo(y));

Alternatively, if you're happy with the normal CompareTo contract which is just stated in terms of negative numbers, positive numbers and 0, you can use CompareTo on its own.

6
  • 1
    I'm actually starting to wonder whether the return value I need isn't the Int32.CompareTo. return after all. In each case, your answer provides the methods I need and is the best answer to my question.. so accepted :)
    – Daan
    Aug 29, 2012 at 19:13
  • 1
    Can you give an example where Int32.CompareTo() returns something other than -1|0|1 ? Aug 30, 2012 at 13:04
  • 5
    @ChrisGessler: Not offhand - but it would be entirely reasonable for it to do so (given the documentation), and I wouldn't want to assume that it never will.
    – Jon Skeet
    Aug 30, 2012 at 13:06
  • 4
    I reflected out the code for Int32.CompareTo() and it doesn't return anything but -1|0|1, however, maybe some other number objects do like Double or Decimal. Aug 30, 2012 at 13:27
  • Why do you also need Math.Sign ?
    – nights
    Jun 21, 2019 at 7:33
15

You can do it without using any .NET calls at all and on 1 line. NOTE: Math.Sign and type.CompareTo both use logical if statements and comparison operators which you said you wanted to avoid.

int result = (((x - y) >> 0x1F) | (int)((uint)(-(x - y)) >> 0x1F));

as a function

//returns 0 if equal
//returns 1 if x > y
//returns -1 if x < y
public int Compare(int x, int y)
{
    return (((x - y) >> 0x1F) | (int)((uint)(-(x - y)) >> 0x1F));
}

Basically, all this does is SHIFT the sign bits all the way to the first position. If the result is unsigned then it will be 0; then it does the same operation and flips the sign bits then ORs them together and the result is wither 1, 0 or -1.

Case where result is -1

IS 12 > 15:

12 - 15 = -3            (11111111111111111111111111111101)
-3 >> 0x1F = -1         (11111111111111111111111111111111)

-(12 - 15) = 3          (00000000000000000000000000000011)
3 >> 0x1F = ((uint)0)=0 (00000000000000000000000000000000) cast to uint so 0

    11111111111111111111111111111111
OR
    00000000000000000000000000000000
=   11111111111111111111111111111111 (-1)

Case where result is 1

IS 15 > 12:

15 - 12 = 3               (00000000000000000000000000000011)
3 >> 0x1F = 0             (00000000000000000000000000000000)

-(15 - 12) = -3           (11111111111111111111111111111101)
-3 >> 0x1F = ((uint)-1)=1 (00000000000000000000000000000001) cast to uint so 1

    00000000000000000000000000000000
OR
    00000000000000000000000000000001
=   00000000000000000000000000000001 (1)

Case where result is 0

IS 15 == 15:

15 - 15 = 0               (00000000000000000000000000000000)
0 >> 0x1F = 0             (00000000000000000000000000000000)

-(15 - 15) = 0            (00000000000000000000000000000000)
0 >> 0x1F = ((uint)0)=0   (00000000000000000000000000000000) cast to uint so 1

    00000000000000000000000000000000
OR
    00000000000000000000000000000000
=   00000000000000000000000000000000 (0)

This should also be much faster than using any calls to Math or any other .NET methods.

0
6
x.CompareTo(y)

Straight from MSDN.

4
  • 1
    Upvoting this one because the MSDN page shows how to coerce the value into -1/0/+1. Without that, CompareTo() doesn't actually do what the OP wants.
    – egrunin
    Aug 29, 2012 at 19:01
  • @egrunin - I don't see in the article where it shows how to coerce the value into -1/0/+1. If you're referring to the cast to the Comparison enum, (Comparison)100 would still be 100, not 1. Aug 30, 2012 at 12:49
  • I haven't run that code, but it appears to claim that (Comparison)100 will return Comparison.GreaterThan, which (if then cast to int) would equal 1.
    – egrunin
    Aug 30, 2012 at 15:48
  • In my tests (C# + .NET 4.0) CompareTo does happen to return either -1, 0 or 1 so the example would work.
    – Juan
    Jul 20, 2013 at 20:02
4

Use the CompareTo() function

int i = 5;
int n = 6;

int c = i.CompareTo(n);

I generally use it in if statements:

int x = 34;
int y = 25;

if(x.CompareTo(y) == 0)
{
  Console.WriteLine("Yes, they are equal");
}
else
{
  Console.WriteLine("No, they are not equal");
}

Edit:

After some people claimed that Int32.CompareTo() could return something other than -1|0|1, I decided to research the possibility myself.

Here's the reflected code for Int32.CompareTo(). I fail to see how either one would ever return anything but -1|0|1.

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public int CompareTo(int value)
{
    if (this < value)
    {
        return -1;
    }
    if (this > value)
    {
        return 1;
    }
    return 0;
}


public int CompareTo(object value)
{
    if (value == null)
    {
        return 1;
    }
    if (!(value is int))
    {
        throw new ArgumentException(Environment.GetResourceString("Arg_MustBeInt32"));
    }
    int num = (int) value;
    if (this < num)
    {
        return -1;
    }
    if (this > num)
    {
        return 1;
    }
    return 0;
}
6
  • 3
    Note that this isn't guaranteed to return -1 or 1.
    – Jon Skeet
    Aug 29, 2012 at 18:55
  • Ahh, yes I almost forgot about that with ints. I generally compare strings which does return -1 | 0 | 1. Aug 29, 2012 at 19:08
  • ints typically do as well. It's just that the contract for CompareTo only guarantees a positive, negative, or zero value and not {-1,0,1}. Aug 29, 2012 at 19:14
  • @AustinSalonen - after some research, I have not found a single example where Int32.CompareTo() returned anything other than -1|0|1. Aug 30, 2012 at 13:08
  • 2
    Indeed. The key word there was "guarantees," which means MS or the Mono team doesn't have to provide that same functionality (or may not have in past releases). Pairing it with Math.Sign does guarantee -1|0|1. Aug 30, 2012 at 14:26
1

It's the Math.Sign() function.

Like this:

return Math.Sign(x-y);
1
  • 3
    My downvote was for your Math.Sign without further explanation, now removed. But with the x-y, it misbehaves on overflow.
    – user743382
    Aug 29, 2012 at 18:56
0

you can try with this code

var result = a.CompareTo(b);
0

Use the CompareTo Method on an integer:

public int c(int x, int y)
{
  return x.CompareTo(y);
}

void Main()
{       
    Console.WriteLine(c(5,3));
    Console.WriteLine(c(3,3));
    Console.WriteLine(c(1,3));
}
0

You tried use compareTo()? Look here: http://msdn.microsoft.com/en-us/library/y2ky8xsk.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.