summaryrefslogtreecommitdiff
path: root/Source/Basetypes/Rational.ssc
blob: ca87b2235f32ddc8e1201caea556c1800db8eb92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
//-----------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation.  All Rights Reserved.
//
//-----------------------------------------------------------------------------
using System;
using Microsoft.Contracts;

namespace Microsoft.Basetypes
{
  using BNM = Microsoft.FSharp.Math.BigRational;

  /// <summary>
  /// The representation of a rational number.
  /// </summary>
  public struct Rational 
  {
    public static readonly Rational ZERO = new Rational ((!)BNM.Zero);
    public static readonly Rational ONE  = new Rational ((!)BNM.One);
    public static readonly Rational MINUS_ONE = new Rational ((!)(-BNM.One));

    private readonly Microsoft.FSharp.Math.BigRational _val;

    private Microsoft.FSharp.Math.BigRational! val {
      get {
        if (_val == null)
          return (!)BNM.Zero;
        else
          return _val;
      }
	}


    //    int numerator;
    //    int denominator;


    // invariant: 0 < denominator || (numerator == 0 && denominator == 0);
    // invariant: numerator != 0 ==> gcd(abs(numerator),denominator) == 1;
    // invariant: numerator == 0 ==> denominator == 1 || denominator == 0;

    private Rational(int x)
    {
      this._val = BNM.FromInt(x);
    }

    public static Rational FromInt(int x) {
      return new Rational(x);
    }

    private Rational(Microsoft.FSharp.Math.BigRational! val) {
      this._val = val;
    }

    public Rational(BigNum num, BigNum den) {
      System.Diagnostics.Debug.Assert(!den.IsZero);
      
      this._val = BNM.FromBigInt(num.val) / BNM.FromBigInt(den.val);
    }

    public static Rational FromInts(int num, int den) {
      return new Rational(BigNum.FromInt(num), BigNum.FromInt(den));
    }

    /// <summary>
    /// Returns the absolute value of the rational.
    /// </summary>
    public Rational Abs()
        ensures result.IsNonNegative;
    {
        if (IsNonNegative) {
            return this;
        } else {
            return -this;
        }
    }

    /// <summary>
    /// Returns a rational whose numerator and denominator, resepctively, are the Gcd
    /// of the numerators and denominators of r and s.  If one of r and s is 0, the absolute
    /// value of the other is returned.  If both are 0, 1 is returned.
    /// </summary>
    public static Rational Gcd(Rational r, Rational s)
        ensures result.IsPositive;
    {
        if (r.IsZero) {
            if (s.IsZero) {
                return ONE;
            } else {
                return s.Abs();
            }
        } else if (s.IsZero) {
            return r.Abs();
        } else {
            return new Rational (r.Numerator.Gcd(s.Numerator),
                                 r.Denominator.Gcd(s.Denominator));
        }
    }
    
    public BigNum Numerator
    {
      get
      {
        // Better way to obtain the numerator?
        // The FSharp library does not seem to offer any methods for this
        string! lin = (!)val.ToString();
        int i = lin.IndexOf('/');
        if (i == -1)
          return new BigNum(BNM.ToBigInt(this.val));
        else
          return BigNum.FromString(lin.Substring(0, i));
      }
    }

    public BigNum Denominator
    {
      get
      {
        // Better way to obtain the numerator?
        // The FSharp library does not seem to offer any methods for this
        string! lin = (!)val.ToString();
        int i = lin.IndexOf('/');
        if (i == -1)
          return BigNum.ONE;
        else
          return BigNum.FromString(lin.Substring(i+1));
      }
    }

    public override string! ToString()
    {
      return String.Format("{0}/{1}", Numerator, Denominator);
    }


    public static bool operator==(Rational r, Rational s)
    {
      return (r.val == s.val);
    }

    public static bool operator!=(Rational r, Rational s)
    {
      return !(r.val == s.val);
    }

    public override bool Equals(object obj)
    {
      if (obj == null) return false;
      return obj is Rational && (Rational)obj == this;
    }

    public override int GetHashCode()
    {
      return this.val.GetHashCode();
    }

    public int Signum {
      get { return this.val.Sign; }
    }

    public bool IsZero
    {
      get
      {
        return Signum == 0;
      }
    }

    public bool IsNonZero
    {
      get
      {
        return Signum != 0;
      }
    }

    public bool IsIntegral
    {
      get
      {
        // better way?
        return !((!)this.val.ToString()).Contains("/");
      }
    }
    
    
    [Pure][Reads(ReadsAttribute.Reads.Nothing)]
    public bool HasValue (int n) { return this == new Rational(n); }

    /// <summary>
    /// Returns the rational as an integer.  Requires the rational to be integral.
    /// </summary>
    public int AsInteger
    {
      get
      {
        System.Diagnostics.Debug.Assert(this.IsIntegral);
        return Numerator.ToIntSafe;
      }
    }

    public BigNum AsBigNum {
      get
      {
        System.Diagnostics.Debug.Assert(this.IsIntegral);
        return new BigNum (BNM.ToBigInt(this.val));
      }
    }

    public double AsDouble
    {
      [Pure]
      get
      {
        if (this.IsZero)
        {
          return 0.0;
        } 
        else
        {
          return (double)Numerator.ToIntSafe / (double)Denominator.ToIntSafe;
        }
      }
    }

    public bool IsNegative
    {
      [Pure]
      get
      {
        return Signum < 0;
      }
    }

    public bool IsPositive
    {
      [Pure]
      get
      {
        return 0 < Signum;
      }
    }

    public bool IsNonNegative
    {
      [Pure]
      get
      {
        return 0 <= Signum;
      }
    }


    public static Rational operator-(Rational r)
    {
      return new Rational ((!)(BNM.Zero -r.val)); // for whatever reason, the Spec# compiler refuses to accept -r.val (unary negation)
    }


    public static Rational operator+(Rational r, Rational s)
    {
      return new Rational ((!)(r.val + s.val));
    }

    public static Rational operator-(Rational r, Rational s)
    {
      return new Rational ((!)(r.val - s.val));
    }

    public static Rational operator*(Rational r, Rational s)
    {
      return new Rational ((!)(r.val * s.val));
    }

    public static Rational operator/(Rational r, Rational s)
    {
      return new Rational ((!)(r.val / s.val));
    }

    public static bool operator<=(Rational r, Rational s)
    {
      return (r.val <= s.val);
    }

    public static bool operator>=(Rational r, Rational s)
    {
      return (r.val >= s.val);
    }

    public static bool operator<(Rational r, Rational s)
    {
      return (r.val < s.val);
    }

    public static bool operator>(Rational r, Rational s)
    {
      return (r.val > s.val);
    }
  }
}