aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/math/number/frac.lux
blob: ccc6bd544aa96f91995f672344968903d364c8a3 (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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
(.module:
  [lux (#- nat int rev)
   ["@" target]
   [abstract
    [hash (#+ Hash)]
    [monoid (#+ Monoid)]
    [equivalence (#+ Equivalence)]
    [codec (#+ Codec)]
    [predicate (#+ Predicate)]
    [order (#+ Order)]
    [monad (#+ do)]]
   [control
    ["." try (#+ Try)]]
   [data
    ["." maybe]
    ["." text]]]
  ["." // #_
   ["#." i64]
   ["#." nat]
   ["#." int]
   ["#." rev]
   ["/#" //]])

(def: #export (= reference sample)
  {#.doc "Frac(tion) equivalence."}
  (-> Frac Frac Bit)
  ("lux f64 =" reference sample))

(def: #export (< reference sample)
  {#.doc "Frac(tion) less-than."}
  (-> Frac Frac Bit)
  ("lux f64 <" reference sample))

(def: #export (<= reference sample)
  {#.doc "Frac(tion) less-than or equal."}
  (-> Frac Frac Bit)
  (or ("lux f64 <" reference sample)
      ("lux f64 =" reference sample)))

(def: #export (> reference sample)
  {#.doc "Frac(tion) greater-than."}
  (-> Frac Frac Bit)
  ("lux f64 <" sample reference))

(def: #export (>= reference sample)
  {#.doc "Frac(tion) greater-than or equal."}
  (-> Frac Frac Bit)
  (or ("lux f64 <" sample reference)
      ("lux f64 =" sample reference)))

(template [<comparison> <name>]
  [(def: #export <name>
     (Predicate Frac)
     (<comparison> +0.0))]

  [..> positive?]
  [..< negative?]
  [..= zero?]
  )

(template [<name> <op> <doc>]
  [(def: #export (<name> param subject)
     {#.doc <doc>}
     (-> Frac Frac Frac)
     (<op> param subject))]

  [+ "lux f64 +" "Frac(tion) addition."]
  [- "lux f64 -" "Frac(tion) substraction."]
  [* "lux f64 *" "Frac(tion) multiplication."]
  [/ "lux f64 /" "Frac(tion) division."]
  [% "lux f64 %" "Frac(tion) remainder."]
  )

(def: #export (/% param subject)
  (-> Frac Frac [Frac Frac])
  [(../ param subject)
   (..% param subject)])

(def: #export negate
  (-> Frac Frac)
  (..* -1.0))

(def: #export (abs x)
  (-> Frac Frac)
  (if (..< +0.0 x)
    (..* -1.0 x)
    x))

(def: #export (signum x)
  (-> Frac Frac)
  (cond (..= +0.0 x) +0.0
        (..< +0.0 x) -1.0
        ## else
        +1.0))

(def: min_exponent -1022)
(def: max_exponent (//int.frac +1023))

(template [<name> <test> <doc>]
  [(def: #export (<name> left right)
     {#.doc <doc>}
     (-> Frac Frac Frac)
     (if (<test> right left)
       left
       right))]

  [min ..< "Frac(tion) minimum."]
  [max ..> "Frac(tion) minimum."]
  )

(def: #export nat
  (-> Frac Nat)
  (|>> "lux f64 i64" .nat))

(def: #export int
  (-> Frac Int)
  (|>> "lux f64 i64"))

(def: mantissa_size Nat 52)
(def: exponent_size Nat 11)

(def: frac_denominator
  (|> -1
      ("lux i64 right-shift" ..exponent_size)
      "lux i64 f64"))

(def: #export rev
  (-> Frac Rev)
  (|>> ..abs
       (..% +1.0)
       (..* ..frac_denominator)
       "lux f64 i64"
       ("lux i64 left-shift" ..exponent_size)))

(structure: #export equivalence
  (Equivalence Frac)
  
  (def: = ..=))

(structure: #export order
  (Order Frac)
  
  (def: &equivalence ..equivalence)
  (def: < ..<))

(def: #export smallest
  Frac
  (///.pow (//int.frac (//int.- (.int ..mantissa_size) ..min_exponent))
           +2.0))

(def: #export biggest
  Frac
  (let [f2^-52 (///.pow (//nat.frac (//nat.- ..mantissa_size 0)) +2.0)
        f2^+1023 (///.pow ..max_exponent +2.0)]
    (|> +2.0
        (..- f2^-52)
        (..* f2^+1023))))

(template [<name> <compose> <identity>]
  [(structure: #export <name>
     (Monoid Frac)
     
     (def: identity <identity>)
     (def: compose <compose>))]

  [addition       ..+   +0.0]
  [multiplication ..*   +1.0]
  [minimum        ..min ..biggest]
  [maximum        ..max (..* -1.0 ..biggest)]
  )

(for {@.python
      (template [<name> <constant> <doc>]
        [(def: #export <name>
           {#.doc <doc>}
           (|> <constant>
               ("python apply" (:coerce Nothing ("python constant" "float")))
               (:coerce Frac)))]

        [not_a_number      "NaN" "Not a number."]
        [positive_infinity "inf" "Positive infinity."]
        )}
     
     (template [<name> <numerator> <doc>]
       [(def: #export <name>
          {#.doc <doc>}
          Frac
          (../ +0.0 <numerator>))]

       [not_a_number      +0.0 "Not a number."]
       [positive_infinity +1.0 "Positive infinity."]
       ))

(def: #export negative_infinity
  {#.doc "Negative infinity."}
  Frac
  (..* -1.0 ..positive_infinity))

(def: #export (not_a_number? number)
  {#.doc "Tests whether a frac is actually not-a-number."}
  (-> Frac Bit)
  (not (..= number number)))

(def: #export (number? value)
  (-> Frac Bit)
  (not (or (..not_a_number? value)
           (..= ..positive_infinity value)
           (..= ..negative_infinity value))))

(structure: #export decimal
  (Codec Text Frac)
  
  (def: (encode x)
    (case x
      -0.0 (let [output ("lux f64 encode" x)]
             (if (text.starts_with? "-" output)
               output
               ("lux text concat" "+" output)))
      _ (if (..< +0.0 x)
          ("lux f64 encode" x)
          ("lux text concat" "+" ("lux f64 encode" x)))))

  (def: (decode input)
    (case ("lux f64 decode" [input])
      (#.Some value)
      (#try.Success value)

      #.None
      (#try.Failure "Could not decode Frac"))))

(def: log/2
  (-> Frac Frac)
  (|>> ///.log
       (../ (///.log +2.0))))

(def: double_bias Nat 1023)

(def: exponent_mask (//i64.mask ..exponent_size))

(def: exponent_offset ..mantissa_size)
(def: sign_offset (//nat.+ ..exponent_size ..exponent_offset))

(template [<cast> <hex> <name>]
  [(def: <name> (|> <hex> (\ //nat.hex decode) try.assume <cast>))]

  [.i64 "FFF8000000000000" not_a_number_bits]
  [.i64 "7FF0000000000000" positive_infinity_bits]
  [.i64 "FFF0000000000000" negative_infinity_bits]
  [.i64 "0000000000000000" positive_zero_bits]
  [.i64 "8000000000000000" negative_zero_bits]
  [.nat "7FF"              special_exponent_bits]
  )

(def: smallest_exponent
  (..log/2 ..smallest))

(def: #export (to_bits input)
  (-> Frac I64)
  (.i64 (cond (..not_a_number? input)
              ..not_a_number_bits

              (..= positive_infinity input)
              ..positive_infinity_bits

              (..= negative_infinity input)
              ..negative_infinity_bits

              (..= +0.0 input)
              (let [reciprocal (../ input +1.0)]
                (if (..= positive_infinity reciprocal)
                  ## Positive zero
                  ..positive_zero_bits
                  ## Negative zero
                  ..negative_zero_bits))

              ## else
              (let [sign_bit (if (..< -0.0 input)
                               1
                               0)
                    input (..abs input)
                    exponent (|> input
                                 ..log/2
                                 ///.floor
                                 (..min ..max_exponent))
                    min_gap (..- (//int.frac ..min_exponent) exponent)
                    power (|> (//nat.frac ..mantissa_size)
                              (..+ (..min +0.0 min_gap))
                              (..- exponent))
                    max_gap (..- ..max_exponent power)
                    mantissa (|> input
                                 (..* (///.pow (..min ..max_exponent power) +2.0))
                                 (..* (if (..> +0.0 max_gap)
                                        (///.pow max_gap +2.0)
                                        +1.0)))
                    exponent_bits (|> (if (..< +0.0 min_gap)
                                        (|> (..int exponent)
                                            (//int.- (..int min_gap))
                                            dec)
                                        (..int exponent))
                                      (//int.+ (.int ..double_bias))
                                      (//i64.and ..exponent_mask))
                    mantissa_bits (..int mantissa)]
                ($_ //i64.or
                    (//i64.left_shift ..sign_offset sign_bit)
                    (//i64.left_shift ..exponent_offset exponent_bits)
                    (//i64.clear ..mantissa_size mantissa_bits)))
              )))

(template [<getter> <size> <offset>]
  [(def: <getter>
     (-> (I64 Any) I64)
     (let [mask (|> 1 (//i64.left_shift <size>) dec (//i64.left_shift <offset>))]
       (|>> (//i64.and mask) (//i64.right_shift <offset>) .i64)))]

  [mantissa ..mantissa_size 0]
  [exponent ..exponent_size ..mantissa_size]
  [sign     1               ..sign_offset]
  )

(def: #export (from_bits input)
  (-> I64 Frac)
  (case [(: Nat (..exponent input))
         (: Nat (..mantissa input))
         (: Nat (..sign input))]
    (^ [(static ..special_exponent_bits) 0 0])
    ..positive_infinity

    (^ [(static ..special_exponent_bits) 0 1])
    ..negative_infinity

    (^ [(static ..special_exponent_bits) _ _])
    ..not_a_number

    ## Positive zero
    [0 0 0] +0.0
    ## Negative zero
    [0 0 1] (..* -1.0 +0.0)

    [E M S]
    (let [sign (if (//nat.= 0 S)
                 +1.0
                 -1.0)
          [mantissa power] (if (//nat.< ..mantissa_size E)
                             [(if (//nat.= 0 E)
                                M
                                (//i64.set ..mantissa_size M))
                              (|> E
                                  (//nat.- ..double_bias)
                                  .int
                                  (//int.max ..min_exponent)
                                  (//int.- (.int ..mantissa_size)))]
                             [(//i64.set ..mantissa_size M)
                              (|> E (//nat.- ..double_bias) (//nat.- ..mantissa_size) .int)])
          exponent (///.pow (//int.frac power) +2.0)]
      (|> (//nat.frac mantissa)
          (..* exponent)
          (..* sign)))))

(def: (split_exponent codec representation)
  (-> (Codec Text Nat) Text (Try [Text Int]))
  (case [("lux text index" 0 "e+" representation)
         ("lux text index" 0 "E+" representation)
         ("lux text index" 0 "e-" representation)
         ("lux text index" 0 "E-" representation)]
    (^template [<factor> <patterns>]
      [<patterns>
       (do try.monad
         [exponent (|> representation
                       ("lux text clip" (//nat.+ 2 split_index) ("lux text size" representation))
                       (\ codec decode))]
         (wrap [("lux text clip" 0 split_index representation)
                (//int.* <factor> (.int exponent))]))])
    ([+1 (^or [(#.Some split_index) #.None #.None #.None]
              [#.None (#.Some split_index) #.None #.None])]
     [-1 (^or [#.None #.None (#.Some split_index) #.None]
              [#.None #.None #.None (#.Some split_index)])])
    
    _
    (#try.Success [representation +0])))

(template [<struct> <nat> <int> <error>]
  [(structure: #export <struct>
     (Codec Text Frac)
     
     (def: (encode value)
       (let [bits (..to_bits value)
             mantissa (..mantissa bits)
             exponent (//int.- (.int ..double_bias) (..exponent bits))
             sign (..sign bits)]
         ($_ "lux text concat"
             (case (.nat sign)
               1 "-"
               0 "+"
               _ (undefined))
             (\ <nat> encode (.nat mantissa))
             ".0E"
             (\ <int> encode exponent))))

     (def: (decode representation)
       (let [negative? (text.starts_with? "-" representation)
             positive? (text.starts_with? "+" representation)]
         (if (or negative? positive?)
           (do {! try.monad}
             [[mantissa exponent] (..split_exponent <nat> representation)
              [whole decimal] (case ("lux text index" 0 "." mantissa)
                                (#.Some split_index)
                                (do !
                                  [decimal (|> mantissa
                                               ("lux text clip" (inc split_index) ("lux text size" mantissa))
                                               (\ <nat> decode))]
                                  (wrap [("lux text clip" 0 split_index mantissa)
                                         decimal]))

                                #.None
                                (#try.Failure ("lux text concat" <error> representation)))
              #let [whole ("lux text clip" 1 ("lux text size" whole) whole)]
              mantissa (\ <nat> decode (case decimal
                                         0 whole
                                         _ ("lux text concat" whole (\ <nat> encode decimal))))
              #let [sign (if negative? 1 0)]]
             (wrap (..from_bits
                    ($_ //i64.or
                        (//i64.left_shift ..sign_offset (.i64 sign))
                        (//i64.left_shift ..mantissa_size (.i64 (//int.+ (.int ..double_bias) exponent)))
                        (//i64.clear ..mantissa_size (.i64 mantissa))))))
           (#try.Failure ("lux text concat" <error> representation))))))]

  [binary //nat.binary //int.binary "Invalid binary syntax: "]
  [octal //nat.octal //int.octal "Invalid octaladecimal syntax: "]
  [hex //nat.hex //int.hex "Invalid hexadecimal syntax: "]
  )

(structure: #export hash
  (Hash Frac)
  
  (def: &equivalence ..equivalence)
  (def: hash ..to_bits))

(def: #export (approximately? margin_of_error standard value)
  (-> Frac Frac Frac Bit)
  (|> value
      (..- standard)
      ..abs
      (..< margin_of_error)))

(def: #export (mod divisor dividend)
  (All [m] (-> Frac Frac Frac))
  (let [remainder (..% divisor dividend)]
    (if (or (and (..< +0.0 divisor)
                 (..> +0.0 remainder))
            (and (..> +0.0 divisor)
                 (..< +0.0 remainder)))
      (..+ divisor remainder)
      remainder)))