Source file float.ml
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
open! Import
open! Printf
module Bytes = Bytes0
include Float0
let raise_s = Error.raise_s
module T = struct
type t = float [@@deriving_inline hash, globalize, sexp, sexp_grammar]
let (hash_fold_t : Ppx_hash_lib.Std.Hash.state -> t -> Ppx_hash_lib.Std.Hash.state) =
hash_fold_float
and (hash : t -> Ppx_hash_lib.Std.Hash.hash_value) =
let func = hash_float in
fun x -> func x
;;
let (globalize : t -> t) = (globalize_float : t -> t)
let t_of_sexp = (float_of_sexp : Sexplib0.Sexp.t -> t)
let sexp_of_t = (sexp_of_float : t -> Sexplib0.Sexp.t)
let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) = float_sexp_grammar
[@@@end]
let hashable : t Hashable.t = { hash; compare; sexp_of_t }
let compare = Float_replace_polymorphic_compare.compare
end
include T
include Comparator.Make (T)
open Float_replace_polymorphic_compare
let invariant (_ : t) = ()
let to_float x = x
let of_float x = x
let of_string s =
try float_of_string s with
| _ -> invalid_argf "Float.of_string %s" s ()
;;
let of_string_opt = float_of_string_opt
external format_float : string -> float -> string = "caml_format_float"
let valid_float_lexem s =
let l = String.length s in
let rec loop i =
if Int_replace_polymorphic_compare.( >= ) i l
then s ^ "."
else (
match s.[i] with
| '0' .. '9' | '-' -> loop (i + 1)
| _ -> s)
in
loop 0
;;
let to_string x =
valid_float_lexem
(let y = format_float "%.15g" x in
if float_of_string y = x then y else format_float "%.17g" x)
;;
let max_value = infinity
let min_value = neg_infinity
let min_positive_subnormal_value = 2. ** -1074.
let min_positive_normal_value = 2. ** -1022.
let zero = 0.
let one = 1.
let minus_one = -1.
let pi = 0x3.243F6A8885A308D313198A2E037073
let sqrt_pi = 0x1.C5BF891B4EF6AA79C3B0520D5DB938
let sqrt_2pi = 0x2.81B263FEC4E0B2CAF9483F5CE459DC
let euler = 0x0.93C467E37DB0C7A4D1BE3F810152CB
let of_int = Int.to_float
let to_int = Int.of_float
let of_int63 i = Int63.to_float i
let of_int64 i = Stdlib.Int64.to_float i
let to_int64 = Stdlib.Int64.of_float
let iround_lbound = lower_bound_for_int Int.num_bits
let iround_ubound = upper_bound_for_int Int.num_bits
let iround_up t =
if t > 0.0
then (
let t' = ceil t in
if t' <= iround_ubound then Some (Int.of_float_unchecked t') else None)
else if t >= iround_lbound
then Some (Int.of_float_unchecked t)
else None
;;
let[@ocaml.inline always] iround_up_exn t =
if t > 0.0
then (
let t' = ceil t in
if t' <= iround_ubound
then Int.of_float_unchecked t'
else invalid_argf "Float.iround_up_exn: argument (%f) is too large" (box t) ())
else if t >= iround_lbound
then Int.of_float_unchecked t
else invalid_argf "Float.iround_up_exn: argument (%f) is too small or NaN" (box t) ()
;;
let iround_down t =
if t >= 0.0
then if t <= iround_ubound then Some (Int.of_float_unchecked t) else None
else (
let t' = floor t in
if t' >= iround_lbound then Some (Int.of_float_unchecked t') else None)
;;
let[@ocaml.inline always] iround_down_exn t =
if t >= 0.0
then
if t <= iround_ubound
then Int.of_float_unchecked t
else invalid_argf "Float.iround_down_exn: argument (%f) is too large" (box t) ()
else (
let t' = floor t in
if t' >= iround_lbound
then Int.of_float_unchecked t'
else
invalid_argf "Float.iround_down_exn: argument (%f) is too small or NaN" (box t) ())
;;
let iround_towards_zero t =
if t >= iround_lbound && t <= iround_ubound
then Some (Int.of_float_unchecked t)
else None
;;
let[@ocaml.inline always] iround_towards_zero_exn t =
if t >= iround_lbound && t <= iround_ubound
then Int.of_float_unchecked t
else
invalid_argf
"Float.iround_towards_zero_exn: argument (%f) is out of range or NaN"
(box t)
()
;;
let round_nearest_lb = -.(2. ** 52.)
let round_nearest_ub = 2. ** 52.
let one_ulp_less_than_half = one_ulp `Down 0.5
let[@ocaml.inline always] add_half_for_round_nearest t =
t
+.
if t = one_ulp_less_than_half
then one_ulp_less_than_half
else 0.5
;;
let iround_nearest_32 t =
if t >= 0.
then (
let t' = add_half_for_round_nearest t in
if t' <= iround_ubound then Some (Int.of_float_unchecked t') else None)
else (
let t' = floor (t +. 0.5) in
if t' >= iround_lbound then Some (Int.of_float_unchecked t') else None)
;;
let iround_nearest_64 t =
if t >= 0.
then
if t < round_nearest_ub
then Some (Int.of_float_unchecked (add_half_for_round_nearest t))
else if t <= iround_ubound
then Some (Int.of_float_unchecked t)
else None
else if t > round_nearest_lb
then Some (Int.of_float_unchecked (floor (t +. 0.5)))
else if t >= iround_lbound
then Some (Int.of_float_unchecked t)
else None
;;
let iround_nearest =
match Word_size.word_size with
| W64 -> iround_nearest_64
| W32 -> iround_nearest_32
;;
let iround_nearest_exn_32 t =
if t >= 0.
then (
let t' = add_half_for_round_nearest t in
if t' <= iround_ubound
then Int.of_float_unchecked t'
else invalid_argf "Float.iround_nearest_exn: argument (%f) is too large" (box t) ())
else (
let t' = floor (t +. 0.5) in
if t' >= iround_lbound
then Int.of_float_unchecked t'
else invalid_argf "Float.iround_nearest_exn: argument (%f) is too small" (box t) ())
;;
let[@ocaml.inline always] iround_nearest_exn_64 t =
if t >= 0.
then
if t < round_nearest_ub
then Int.of_float_unchecked (add_half_for_round_nearest t)
else if t <= iround_ubound
then Int.of_float_unchecked t
else invalid_argf "Float.iround_nearest_exn: argument (%f) is too large" (box t) ()
else if t > round_nearest_lb
then Int.of_float_unchecked (floor (t +. 0.5))
else if t >= iround_lbound
then Int.of_float_unchecked t
else
invalid_argf "Float.iround_nearest_exn: argument (%f) is too small or NaN" (box t) ()
;;
let iround_nearest_exn =
match Word_size.word_size with
| W64 -> iround_nearest_exn_64
| W32 -> iround_nearest_exn_32
;;
let[@inline] iround_exn ?(dir = `Nearest) t =
match dir with
| `Zero -> iround_towards_zero_exn t
| `Nearest -> iround_nearest_exn t
| `Up -> iround_up_exn t
| `Down -> iround_down_exn t
;;
let iround ?(dir = `Nearest) t =
try Some (iround_exn ~dir t) with
| _ -> None
;;
let is_inf t = 1. /. t = 0.
let is_finite t = t -. t = 0.
let min_inan (x : t) y =
if is_nan y then x else if is_nan x then y else if x < y then x else y
;;
let max_inan (x : t) y =
if is_nan y then x else if is_nan x then y else if x > y then x else y
;;
let add = ( +. )
let sub = ( -. )
let neg = ( ~-. )
let abs = abs_float
let scale = ( *. )
let square x = x *. x
module Parts : sig
type t
val fractional : t -> float
val integral : t -> float
val modf : float -> t
end = struct
type t = float * float
let fractional t = fst t
let integral t = snd t
let modf = modf
end
let modf = Parts.modf
let round_down = floor
let round_up = ceil
let round_towards_zero t = if t >= 0. then round_down t else round_up t
let[@ocaml.inline] round_nearest_inline t =
if t > round_nearest_lb && t < round_nearest_ub
then floor (add_half_for_round_nearest t)
else t +. 0.
;;
let round_nearest t = (round_nearest_inline [@ocaml.inlined always]) t
let round_nearest_half_to_even t =
if t <= round_nearest_lb || t >= round_nearest_ub
then t +. 0.
else (
let floor = floor t in
let ceil_or_succ = floor +. 1. in
let diff_floor = t -. floor in
let diff_ceil = ceil_or_succ -. t in
if diff_floor < diff_ceil
then floor
else if diff_floor > diff_ceil
then ceil_or_succ
else if
mod_float floor 2. = 0.
then floor
else ceil_or_succ)
;;
let int63_round_lbound = lower_bound_for_int Int63.num_bits
let int63_round_ubound = upper_bound_for_int Int63.num_bits
let int63_round_up_exn t =
if t > 0.0
then (
let t' = ceil t in
if t' <= int63_round_ubound
then Int63.of_float_unchecked t'
else
invalid_argf
"Float.int63_round_up_exn: argument (%f) is too large"
(Float0.box t)
())
else if t >= int63_round_lbound
then Int63.of_float_unchecked t
else
invalid_argf
"Float.int63_round_up_exn: argument (%f) is too small or NaN"
(Float0.box t)
()
;;
let int63_round_down_exn t =
if t >= 0.0
then
if t <= int63_round_ubound
then Int63.of_float_unchecked t
else
invalid_argf
"Float.int63_round_down_exn: argument (%f) is too large"
(Float0.box t)
()
else (
let t' = floor t in
if t' >= int63_round_lbound
then Int63.of_float_unchecked t'
else
invalid_argf
"Float.int63_round_down_exn: argument (%f) is too small or NaN"
(Float0.box t)
())
;;
let int63_round_nearest_portable_alloc_exn t0 =
let t = (round_nearest_inline [@ocaml.inlined always]) t0 in
if t > 0.
then
if t <= int63_round_ubound
then Int63.of_float_unchecked t
else
invalid_argf
"Float.int63_round_nearest_portable_alloc_exn: argument (%f) is too large"
(box t0)
()
else if t >= int63_round_lbound
then Int63.of_float_unchecked t
else
invalid_argf
"Float.int63_round_nearest_portable_alloc_exn: argument (%f) is too small or NaN"
(box t0)
()
;;
let[@inline] int63_round_nearest_arch64_noalloc_exn f =
Int63.of_int (iround_nearest_exn f)
;;
let int63_round_nearest_exn =
match Word_size.word_size with
| W64 -> int63_round_nearest_arch64_noalloc_exn
| W32 -> int63_round_nearest_portable_alloc_exn
;;
let round ?(dir = `Nearest) t =
match dir with
| `Nearest -> round_nearest t
| `Down -> round_down t
| `Up -> round_up t
| `Zero -> round_towards_zero t
;;
module Class = struct
type t =
| Infinite
| Nan
| Normal
| Subnormal
| Zero
[@@deriving_inline compare ~localize, enumerate, sexp, sexp_grammar]
let compare__local = (Stdlib.compare : t -> t -> int)
let compare = (fun a b -> compare__local a b : t -> t -> int)
let all = ([ Infinite; Nan; Normal; Subnormal; Zero ] : t list)
let t_of_sexp =
(let error_source__007_ = "float.ml.Class.t" in
function
| Sexplib0.Sexp.Atom ("infinite" | "Infinite") -> Infinite
| Sexplib0.Sexp.Atom ("nan" | "Nan") -> Nan
| Sexplib0.Sexp.Atom ("normal" | "Normal") -> Normal
| Sexplib0.Sexp.Atom ("subnormal" | "Subnormal") -> Subnormal
| Sexplib0.Sexp.Atom ("zero" | "Zero") -> Zero
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("infinite" | "Infinite") :: _) as
sexp__008_ -> Sexplib0.Sexp_conv_error.stag_no_args error_source__007_ sexp__008_
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("nan" | "Nan") :: _) as sexp__008_ ->
Sexplib0.Sexp_conv_error.stag_no_args error_source__007_ sexp__008_
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("normal" | "Normal") :: _) as sexp__008_ ->
Sexplib0.Sexp_conv_error.stag_no_args error_source__007_ sexp__008_
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("subnormal" | "Subnormal") :: _) as
sexp__008_ -> Sexplib0.Sexp_conv_error.stag_no_args error_source__007_ sexp__008_
| Sexplib0.Sexp.List (Sexplib0.Sexp.Atom ("zero" | "Zero") :: _) as sexp__008_ ->
Sexplib0.Sexp_conv_error.stag_no_args error_source__007_ sexp__008_
| Sexplib0.Sexp.List (Sexplib0.Sexp.List _ :: _) as sexp__006_ ->
Sexplib0.Sexp_conv_error.nested_list_invalid_sum error_source__007_ sexp__006_
| Sexplib0.Sexp.List [] as sexp__006_ ->
Sexplib0.Sexp_conv_error.empty_list_invalid_sum error_source__007_ sexp__006_
| sexp__006_ ->
Sexplib0.Sexp_conv_error.unexpected_stag error_source__007_ sexp__006_
: Sexplib0.Sexp.t -> t)
;;
let sexp_of_t =
(function
| Infinite -> Sexplib0.Sexp.Atom "Infinite"
| Nan -> Sexplib0.Sexp.Atom "Nan"
| Normal -> Sexplib0.Sexp.Atom "Normal"
| Subnormal -> Sexplib0.Sexp.Atom "Subnormal"
| Zero -> Sexplib0.Sexp.Atom "Zero"
: t -> Sexplib0.Sexp.t)
;;
let (t_sexp_grammar : t Sexplib0.Sexp_grammar.t) =
{ untyped =
Variant
{ case_sensitivity = Case_sensitive_except_first_character
; clauses =
[ No_tag { name = "Infinite"; clause_kind = Atom_clause }
; No_tag { name = "Nan"; clause_kind = Atom_clause }
; No_tag { name = "Normal"; clause_kind = Atom_clause }
; No_tag { name = "Subnormal"; clause_kind = Atom_clause }
; No_tag { name = "Zero"; clause_kind = Atom_clause }
]
}
}
;;
[@@@end]
let to_string t = string_of_sexp (sexp_of_t t)
let of_string s = t_of_sexp (sexp_of_string s)
end
let classify t =
let module C = Class in
match classify_float t with
| FP_normal -> C.Normal
| FP_subnormal -> C.Subnormal
| FP_zero -> C.Zero
| FP_infinite -> C.Infinite
| FP_nan -> C.Nan
;;
let insert_underscores ?(delimiter = '_') ?(strip_zero = false) string =
match String.lsplit2 string ~on:'.' with
| None -> Int_string_conversions.insert_delimiter string ~delimiter
| Some (left, right) ->
let left = Int_string_conversions.insert_delimiter left ~delimiter in
let right =
if strip_zero then String.rstrip right ~drop:(fun c -> Char.( = ) c '0') else right
in
(match right with
| "" -> left
| _ -> left ^ "." ^ right)
;;
let to_string_hum ?delimiter ?(decimals = 3) ?strip_zero ?(explicit_plus = false) f =
if Int_replace_polymorphic_compare.( < ) decimals 0
then invalid_argf "to_string_hum: invalid argument ~decimals=%d" decimals ();
match classify f with
| Class.Infinite -> if f > 0. then "inf" else "-inf"
| Class.Nan -> "nan"
| Class.Normal | Class.Subnormal | Class.Zero ->
let s =
if explicit_plus then sprintf "%+.*f" decimals f else sprintf "%.*f" decimals f
in
insert_underscores s ?delimiter ?strip_zero
;;
let sexp_of_t t =
let sexp = sexp_of_t t in
match !Sexp.of_float_style with
| `No_underscores -> sexp
| `Underscores ->
(match sexp with
| List _ ->
raise_s
(Sexp.message
"[sexp_of_float] produced strange sexp"
[ "sexp", Sexp.sexp_of_t sexp ])
| Atom string ->
if String.contains string 'E' then sexp else Atom (insert_underscores string))
;;
let to_padded_compact_string_custom t ?(prefix = "") ~kilo ~mega ~giga ~tera ?peta () =
let iround_ratio_exn ~numerator ~denominator =
let k = floor (numerator /. denominator) in
let lower = denominator *. k in
let higher = denominator *. (k +. 1.) in
let diff_right = higher -. numerator in
let diff_left = numerator -. lower in
let k = iround_nearest_exn k in
if diff_right < diff_left
then k + 1
else if diff_right > diff_left
then k
else if
Int_replace_polymorphic_compare.( = ) (k mod 2) 0
then k
else k + 1
in
match classify t with
| Class.Infinite -> if t < 0.0 then "-inf " else "inf "
| Class.Nan -> "nan "
| Class.Subnormal | Class.Normal | Class.Zero ->
let go t =
let conv_one t =
assert (0. <= t && t < 999.95);
let x = prefix ^ format_float "%.1f" t in
if String.is_suffix x ~suffix:".0"
then (
let x = Bytes.of_string x in
let n = Bytes.length x in
Bytes.set x (n - 1) ' ';
Bytes.set x (n - 2) ' ';
Bytes.unsafe_to_string ~no_mutation_while_string_reachable:x)
else x
in
let conv mag t denominator =
assert (
(denominator = 100. && t >= 999.95)
|| (denominator >= 100_000. && t >= round_nearest (denominator *. 9.999_5)));
assert (t < round_nearest (denominator *. 9_999.5));
let i, d =
let k = iround_ratio_exn ~numerator:t ~denominator in
k / 10, k mod 10
in
let open Int_replace_polymorphic_compare in
assert (0 <= i && i < 1000);
assert (0 <= d && d < 10);
if d = 0
then sprintf "%s%d%s " prefix i mag
else sprintf "%s%d%s%d" prefix i mag d
in
if t < 999.95E0
then conv_one t
else if t < 999.95E3
then conv kilo t 100.
else if t < 999.95E6
then conv mega t 100_000.
else if t < 999.95E9
then conv giga t 100_000_000.
else if t < 999.95E12
then conv tera t 100_000_000_000.
else (
match peta with
| None -> sprintf "%s%.1e" prefix t
| Some peta ->
if t < 999.95E15
then conv peta t 100_000_000_000_000.
else sprintf "%s%.1e" prefix t)
in
if t >= 0. then go t else "-" ^ go ~-.t
;;
let to_padded_compact_string t =
to_padded_compact_string_custom t ~kilo:"k" ~mega:"m" ~giga:"g" ~tera:"t" ~peta:"p" ()
;;
let int_pow x n =
let open Int_replace_polymorphic_compare in
if n = 0
then 1.
else (
let x = ref (x +. -0.) in
let n = ref n in
let accum = ref 1. in
if !n < 0
then (
x := 1. /. !x;
n := ~- (!n);
if !n < 0
then (
accum := !x;
decr n));
while !n > 1 do
if !n land 1 <> 0 then accum := !x *. !accum;
x := !x *. !x;
n := !n lsr 1
done;
!x *. !accum)
;;
let round_gen x ~how =
if x = 0.
then 0.
else if not (is_finite x)
then x
else (
let sd, dd =
match how with
| `significant_digits sd ->
let dd = sd - to_int (round_up (log10 (abs x))) in
sd, dd
| `decimal_digits dd ->
let sd = dd + to_int (round_up (log10 (abs x))) in
sd, dd
in
let open Int_replace_polymorphic_compare in
if sd < 0
then 0.
else if sd >= 17
then x
else (
let abs_dd = Int.abs dd in
if abs_dd > 22 || sd >= 16
then of_string (sprintf "%.*g" sd x)
else (
let order = int_pow 10. abs_dd in
if dd >= 0
then round_nearest_half_to_even (x *. order) /. order
else round_nearest_half_to_even (x /. order) *. order)))
;;
let round_significant x ~significant_digits =
if Int_replace_polymorphic_compare.( <= ) significant_digits 0
then
invalid_argf
"Float.round_significant: invalid argument significant_digits:%d"
significant_digits
()
else round_gen x ~how:(`significant_digits significant_digits)
;;
let round_decimal x ~decimal_digits = round_gen x ~how:(`decimal_digits decimal_digits)
let between t ~low ~high = low <= t && t <= high
let clamp_exn t ~min ~max =
assert (min <= max);
clamp_unchecked
~to_clamp_maybe_nan:t
~min_which_is_not_nan:min
~max_which_is_not_nan:max
;;
let clamp t ~min ~max =
if min <= max
then
Ok
(clamp_unchecked
~to_clamp_maybe_nan:t
~min_which_is_not_nan:min
~max_which_is_not_nan:max)
else
Or_error.error_s
(Sexp.message
"clamp requires [min <= max]"
[ "min", T.sexp_of_t min; "max", T.sexp_of_t max ])
;;
let ( + ) = ( +. )
let ( - ) = ( -. )
let ( * ) = ( *. )
let ( ** ) = ( ** )
let ( / ) = ( /. )
let ( % ) = ( %. )
let ( ~- ) = ( ~-. )
let[@inline] sign_exn t : Sign.t =
if t > 0.
then Pos
else if t < 0.
then Neg
else if t = 0.
then Zero
else Error.raise_s (Sexp.message "Float.sign_exn of NAN" [ "", sexp_of_t t ])
;;
let sign_or_nan t : Sign_or_nan.t =
if t > 0. then Pos else if t < 0. then Neg else if t = 0. then Zero else Nan
;;
let ieee_negative t =
let bits = Stdlib.Int64.bits_of_float t in
Poly.(bits < Stdlib.Int64.zero)
;;
let exponent_bits = 11
let mantissa_bits = 52
let exponent_mask64 = Int64.(shift_left one exponent_bits - one)
let exponent_mask = Int64.to_int_exn exponent_mask64
let mantissa_mask = Int63.(shift_left one mantissa_bits - one)
let mantissa_mask64 = Int63.to_int64 mantissa_mask
let ieee_exponent t =
let bits = Stdlib.Int64.bits_of_float t in
Int64.(bit_and (shift_right_logical bits mantissa_bits) exponent_mask64)
|> Stdlib.Int64.to_int
;;
let ieee_mantissa t =
let bits = Stdlib.Int64.bits_of_float t in
(Int63.of_int64_trunc [@inlined]) Stdlib.Int64.(logand bits mantissa_mask64)
;;
let create_ieee_exn ~negative ~exponent ~mantissa =
if Int.(bit_and exponent exponent_mask <> exponent)
then failwithf "exponent %d out of range [0, %d]" exponent exponent_mask ()
else if Int63.(bit_and mantissa mantissa_mask <> mantissa)
then
failwithf
"mantissa %s out of range [0, %s]"
(Int63.to_string mantissa)
(Int63.to_string mantissa_mask)
()
else (
let sign_bits = if negative then Stdlib.Int64.min_int else Stdlib.Int64.zero in
let expt_bits =
Stdlib.Int64.shift_left (Stdlib.Int64.of_int exponent) mantissa_bits
in
let mant_bits = Int63.to_int64 mantissa in
let bits = Stdlib.Int64.(logor sign_bits (logor expt_bits mant_bits)) in
Stdlib.Int64.float_of_bits bits)
;;
let create_ieee ~negative ~exponent ~mantissa =
Or_error.try_with (fun () -> create_ieee_exn ~negative ~exponent ~mantissa)
;;
module Terse = struct
type nonrec t = t
let t_of_sexp = t_of_sexp
let to_string x = Printf.sprintf "%.8G" x
let sexp_of_t x = Sexp.Atom (to_string x)
let of_string x = of_string x
let t_sexp_grammar = t_sexp_grammar
end
include Comparable.With_zero (struct
include T
let zero = zero
end)
let is_positive t = t > 0.
let is_non_negative t = t >= 0.
let is_negative t = t < 0.
let is_non_positive t = t <= 0.
include Pretty_printer.Register (struct
include T
let module_name = "Base.Float"
let to_string = to_string
end)
module O = struct
let ( + ) = ( + )
let ( - ) = ( - )
let ( * ) = ( * )
let ( / ) = ( / )
let ( % ) = ( % )
let ( ~- ) = ( ~- )
let ( ** ) = ( ** )
include (Float_replace_polymorphic_compare : Comparisons.Infix with type t := t)
let abs = abs
let neg = neg
let zero = zero
let of_int = of_int
let of_float x = x
end
module O_dot = struct
let ( *. ) = ( * )
let ( +. ) = ( + )
let ( -. ) = ( - )
let ( /. ) = ( / )
let ( %. ) = ( % )
let ( ~-. ) = ( ~- )
let ( **. ) = ( ** )
end
module Private = struct
let box = box
let clamp_unchecked = clamp_unchecked
let lower_bound_for_int = lower_bound_for_int
let upper_bound_for_int = upper_bound_for_int
let specialized_hash = hash_float
let one_ulp_less_than_half = one_ulp_less_than_half
let int63_round_nearest_portable_alloc_exn = int63_round_nearest_portable_alloc_exn
let int63_round_nearest_arch64_noalloc_exn = int63_round_nearest_arch64_noalloc_exn
let iround_nearest_exn_64 = iround_nearest_exn_64
end
include Float_replace_polymorphic_compare
let min (x : t) y = if x < y || is_nan x then x else y
let max (x : t) y = if x > y || is_nan x then x else y