0

I have a simple Method that returns the exponential value from a given number:

    public int Exp(int num)
    {
        return Convert.ToInt32(System.Math.Exp(num));
    }

When running Pex I get an OverFlowException in the Summary/Exception field for a certain large number: 1969057606.

How could I create a Post Condition using Contract.Ensure()? I tried the following but it does not do anything:

Contract.Ensures(Contract.Result<int>() < 2147483647);

// This is because the max value an int variable can hold is 2147483647
Gabriele Petronella
  • 106,943
  • 21
  • 217
  • 235
  • You should use `int.MaxValue` rather than the actual number, it's a lot easier for someone looking at the code to read and parse. – Bryan Anderson Apr 21 '13 at 18:46

1 Answers1

0

Contract.Ensures is used to assert something about the state of your class after the function is run or, in this case, the result of the function regardless of what the input was. You need to add a Contract.Requires such that e^num <= int.MaxValue, e.g.

Contract.Requires<ArgumentOutOfRangeException>(num <= Math.Floor(Math.Log(int.MaxValue)))

Although you'd probably want to pull the max value calculation out into a constant.

public static readonly int MAX_EXPONENT = Math.Floor(Math.Log(int.MaxValue));
...
Contract.Requires<ArgumentOutOfRangeException>(num <= MAX_EXPONENT)
Bryan Anderson
  • 15,969
  • 8
  • 68
  • 83