Debian Codegraph @

lib/mlrisc-lib/MLRISC/library/fixed-point.sml

raw
1 (*
2 * A simple fixed point datatype
3 *
4 * -- Allen
5 *)
6
7 functor FixedPoint (val decimal_bits : int) : FIXED_POINT =
8 struct
9
10 structure W = Word31
11
12 infix << >>
13 infix & ||
14
15 val decimal_places = (decimal_bits + 2) div 3
16 val realToString = Real.fmt (StringCvt.FIX(SOME decimal_places))
17
18 val op<< = W.<<
19 val op>> = W.>>
20 val op& = W.andb
21 val op|| = W.orb
22 val op div = W.div
23 val word = W.fromInt
24 val int = W.toInt
25
26 type fixed_point = W.word
27
28 val bits = word decimal_bits
29 val bits2 = bits >> 0w1
30 val bits4 = bits >> 0w2
31
32 val zero = 0w0
33 val one = 0w1 << bits
34 val realOne = Real.fromInt(int one)
35
36 val compare = W.compare
37
38 val op* = fn(i:fixed_point,j:fixed_point) => W.*(i >> bits2,j >> bits2)
39 val op/ = fn(i:fixed_point,j:fixed_point) => (i << bits) div j
40
41 val mask = one - 0w1
42
43 fun fromInt i = (word i) << bits
44 fun fixed_point(a,b) = let val b' = word b
45 in (((word a) << bits) + (b' >> 0w1)) div b' end
46 fun fromReal r = word(Real.round(Real.*(r, realOne)))
47 fun toReal p = Real./(Real.fromInt(int p), realOne)
48 fun toWord f = f
49 fun toString p = realToString(toReal p)
50 handle Overflow => "inf"
51
52 fun scale(i,j) = W.*(i, word j)
53 fun i div j = W.div(i,word j)
54
55 val min = W.min
56 val max = W.max
57
58 end
59