-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathdecimal.ex
More file actions
3068 lines (2367 loc) · 93.5 KB
/
Copy pathdecimal.ex
File metadata and controls
3068 lines (2367 loc) · 93.5 KB
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
defmodule Decimal do
@moduledoc """
Decimal arithmetic on arbitrary precision floating-point numbers.
A number is represented by a signed coefficient and exponent such that: `sign
* coefficient * 10 ^ exponent`. All numbers are represented and calculated
exactly, but the result of an operation may be rounded depending on the
context the operation is performed with, see: `Decimal.Context`. Trailing
zeros in the coefficient are never truncated to preserve the number of
significant digits unless explicitly done so.
There are also special values such as NaN (not a number) and ±Infinity.
-0 and +0 are two distinct values.
Some operation results are not defined and will return NaN.
This kind of NaN is quiet, any operation returning a number will return
NaN when given a quiet NaN (the NaN value will flow through all operations).
Exceptional conditions are grouped into signals, each signal has a flag and a
trap enabler in the context. Whenever a signal is triggered it's flag is set
in the context and will be set until explicitly cleared. If the signal is trap
enabled `Decimal.Error` will be raised.
## Specifications
* [IBM's General Decimal Arithmetic Specification](http://speleotrove.com/decimal/decarith.html)
* [IEEE standard 854-1987](http://web.archive.org/web/20150908012941/http://754r.ucbtest.org/standards/854.pdf)
This library follows the above specifications for reference of arithmetic
operation implementations, but the public APIs may differ to provide a
more idiomatic Elixir interface.
The specification models the sign of the number as 1, for a negative number,
and 0 for a positive number. Internally this implementation models the sign as
1 or -1 such that the complete number will be `sign * coefficient *
10 ^ exponent` and will refer to the sign in documentation as either *positive*
or *negative*.
The default `Decimal.Context` follows IEEE 754 decimal128: `precision` is
34, `emax` is 6 144, and `emin` is -6 143. Operation results whose adjusted
exponent leaves that band signal overflow or underflow. Clamped is still
not signalled.
## Large exponents and untrusted input
Decimal can represent compact values with very large exponents, such as
`1e1000000`. These values are valid decimals, but some APIs may need memory
or CPU proportional to the expanded size of the number.
`parse/1`, `parse/2`, `cast/1`, `cast/2`, `to_string/2`, and `to_string/3`
apply IEEE 754 decimal128 limits by default: `:max_digits` of 34,
`:max_exponent` of 6 144, and a `:max_digits` for output of 6 178
(precision + emax — large enough to render any in-range decimal128 in any
format). These defaults reject the pathological inputs described in
CVE-2026-32686 without materializing them. Pass options on the explicit
arities to override; pass `:infinity` to disable a limit entirely.
## Protocol Implementations
`Decimal` implements the following protocols:
### `Inspect`
iex> inspect(Decimal.new("1.00"))
"Decimal.new(\\"1.00\\")"
### `String.Chars`
iex> to_string(Decimal.new("1.00"))
"1.00"
### `JSON.Encoder`
_(If running Elixir 1.18+.)_
By default, decimals are encoded as strings to preserve precision:
iex> JSON.encode!(Decimal.new("1.00"))
"\\"1.00\\""
To change that, pass a custom encoder to `JSON.encode!/2`. The following encodes
decimals as floats:
iex> encoder = fn
...> %Decimal{} = decimal, _encoder ->
...> if Decimal.inf?(decimal) or Decimal.nan?(decimal) do
...> raise ArgumentError, "\#{inspect(decimal)} cannot be encoded to JSON"
...> end
...>
...> Decimal.to_string(decimal)
...>
...> other, encoder ->
...> JSON.protocol_encode(other, encoder)
...> end
...>
iex> JSON.encode!(%{x: Decimal.new("1.00")}, encoder)
"{\\"x\\":1.00}"
"""
import Bitwise
import Kernel, except: [abs: 1, div: 2, max: 2, min: 2, rem: 2, round: 1]
import Decimal.Macros
alias Decimal.Context
alias Decimal.Error
@power_of_2_to_52 4_503_599_627_370_496
@typedoc """
The coefficient of the power of `10`. Non-negative because the sign is stored separately in `sign`.
* `non_neg_integer` - when the `t` represents a number, instead of one of the special values below.
* `:NaN` - Not a Number.
* `:inf` - Infinity.
"""
@type coefficient :: non_neg_integer | :NaN | :inf
@typedoc """
The exponent to which `10` is raised.
"""
@type exponent :: integer
@typedoc """
* `1` for positive
* `-1` for negative
"""
@type sign :: 1 | -1
@type signal ::
:invalid_operation
| :division_by_zero
| :rounded
| :inexact
| :overflow
| :underflow
@type compare_result ::
:lt | :gt | :eq
@typedoc """
Rounding algorithm.
See `Decimal.Context` for more information.
"""
@type rounding ::
:down
| :half_up
| :half_even
| :ceiling
| :floor
| :half_down
| :up
@type parse_option ::
{:max_digits, non_neg_integer | :infinity}
| {:max_exponent, non_neg_integer | :infinity}
@type to_string_option ::
{:max_digits, non_neg_integer | :infinity}
# IEEE 754 decimal128 defaults: precision = 34, emax = 6_144, emin = -6_143.
# The to_string default is precision + emax (34 + 6_144), which is the
# worst-case `:normal` digit-character count for any in-range decimal128
# value.
@default_max_digits 34
@default_max_exponent 6_144
@default_to_string_max_digits 6_178
# A literal map is a compile-time constant, so the limits `parse/1`, `new/1`
# and `cast/1` always use cost no allocation.
@default_parse_limits %{max_digits: @default_max_digits, max_exponent: @default_max_exponent}
# Below 10^2000 the BIF `:erlang.integer_to_binary/1` is fast enough; for
# larger integers `integer_to_decimal_iodata/3` recursively splits on a
# power of 10 (down to chunks of `@decimal_conversion_leaf_digits` digits)
# to avoid the quadratic cost of the BIF on very large bignums.
@decimal_conversion_direct_limit :erlang.binary_to_integer("1" <> String.duplicate("0", 2_000))
@decimal_conversion_leaf_digits 1_024
# Rational approximation of log10(2) used by `integer_decimal_digit_count/1`
# to estimate decimal digit count from bit length:
#
# log10(2) ≈ 0.30102999566398119521...
# @log10_2_num = round(log10(2) * 2^48) = 84_732_411_018_728
# @log10_2_den = 2^48 = 281_474_976_710_656
#
# 2^48 keeps both constants below 2^47/2^48 so `(bits - 1) * @log10_2_num`
# stays a cheap small-bignum multiply, while the approximation is exact
# enough that `digits = div((bits - 1) * num, den) + 1` is off by at most
# one for any bit length we care about; the caller then nudges by ±1.
@log10_2_num 84_732_411_018_728
@log10_2_den 281_474_976_710_656
@normalize_chunk 16
@normalize_chunk_pow 10_000_000_000_000_000
@typedoc """
This implementation models the `sign` as `1` or `-1` such that the complete number will be: `sign * coef * 10 ^ exp`.
* `coef` - the coefficient of the power of `10`.
* `exp` - the exponent of the power of `10`.
* `sign` - `1` for positive, `-1` for negative.
"""
@type t :: %__MODULE__{
sign: sign,
coef: coefficient,
exp: exponent
}
@type decimal :: t | integer | String.t()
defstruct sign: 1, coef: 0, exp: 0
defmacrop error(flags, reason, result, context \\ nil) do
quote bind_quoted: binding() do
case handle_error(flags, reason, result, context) do
{:ok, result} -> result
{:error, error} -> raise Error, error
end
end
end
@doc """
Returns `true` if number is NaN, otherwise `false`.
## Examples
iex> Decimal.nan?(Decimal.new("NaN"))
true
iex> Decimal.nan?(Decimal.new(42))
false
"""
@spec nan?(t) :: boolean
def nan?(%Decimal{coef: :NaN}), do: true
def nan?(%Decimal{}), do: false
@doc """
Returns `true` if number is ±Infinity, otherwise `false`.
## Examples
iex> Decimal.inf?(Decimal.new("+Infinity"))
true
iex> Decimal.inf?(Decimal.new("-Infinity"))
true
iex> Decimal.inf?(Decimal.new("1.5"))
false
"""
@spec inf?(t) :: boolean
def inf?(%Decimal{coef: :inf}), do: true
def inf?(%Decimal{}), do: false
@doc """
Returns `true` if argument is a decimal number, otherwise `false`.
## Examples
iex> Decimal.is_decimal(Decimal.new(42))
true
iex> Decimal.is_decimal(42)
false
Allowed in guard tests on OTP 21+.
"""
doc_since("1.9.0")
defmacro is_decimal(term)
if function_exported?(:erlang, :is_map_key, 2) do
defmacro is_decimal(term) do
case __CALLER__.context do
nil ->
quote do
case unquote(term) do
%Decimal{} -> true
_ -> false
end
end
:match ->
raise ArgumentError,
"invalid expression in match, is_decimal is not allowed in patterns " <>
"such as function clauses, case clauses or on the left side of the = operator"
:guard ->
quote do
is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and
:erlang.map_get(:__struct__, unquote(term)) == Decimal
end
end
end
else
# TODO: remove when we require Elixir v1.10
defmacro is_decimal(term) do
quote do
case unquote(term) do
%Decimal{} -> true
_ -> false
end
end
end
end
@doc """
The absolute value of given number. Sets the number's sign to positive.
## Examples
iex> Decimal.abs(Decimal.new("1"))
Decimal.new("1")
iex> Decimal.abs(Decimal.new("-1"))
Decimal.new("1")
iex> Decimal.abs(Decimal.new("NaN"))
Decimal.new("NaN")
"""
@spec abs(t) :: t
def abs(%Decimal{coef: :NaN} = num), do: %{num | sign: 1}
def abs(%Decimal{} = num), do: context(%{num | sign: 1})
@doc """
Adds two numbers together.
## Exceptional conditions
* If one number is -Infinity and the other +Infinity, `:invalid_operation` will
be signalled.
## Examples
iex> Decimal.add(1, "1.1")
Decimal.new("2.1")
iex> Decimal.add(1, "Inf")
Decimal.new("Infinity")
"""
@spec add(decimal, decimal) :: t
def add(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1
def add(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2
def add(%Decimal{coef: :inf, sign: sign} = num1, %Decimal{coef: :inf, sign: sign} = num2) do
if num1.exp > num2.exp do
num1
else
num2
end
end
def add(%Decimal{coef: :inf}, %Decimal{coef: :inf}),
do: error(:invalid_operation, "adding +Infinity and -Infinity", %Decimal{coef: :NaN})
def add(%Decimal{coef: :inf} = num1, %Decimal{}), do: num1
def add(%Decimal{}, %Decimal{coef: :inf} = num2), do: num2
def add(%Decimal{} = num1, %Decimal{} = num2) do
%Decimal{sign: sign1, coef: coef1, exp: exp1} = num1
%Decimal{sign: sign2, coef: coef2, exp: exp2} = num2
ctx = Context.get()
cond do
coef1 == 0 and coef2 == 0 ->
sign = add_sign(sign1, sign2, 0, ctx)
context(%Decimal{sign: sign, coef: 0, exp: Kernel.min(exp1, exp2)}, [], false, ctx)
coef1 == 0 ->
add_zero(num1, num2, ctx)
coef2 == 0 ->
add_zero(num2, num1, ctx)
# The bounded path below guards against coefficient amplification from an
# exponent gap (CVE-2026-32686). Equal exponents need no alignment, so
# there is nothing to amplify: the bounded path would settle on
# `base_exp == exp1`, scale both coefficients by 10^0 and compute this
# very sum. Reaching that conclusion costs counting both coefficients'
# digits, which is all `add_bounded?/3` does.
exp1 == exp2 ->
add_coefs(sign1, coef1, sign2, coef2, exp1, ctx)
add_bounded?(num1, num2, ctx) ->
add_bounded(num1, num2, ctx)
true ->
{coef1, coef2} = add_align(coef1, exp1, coef2, exp2)
add_coefs(sign1, coef1, sign2, coef2, Kernel.min(exp1, exp2), ctx)
end
end
def add(num1, num2), do: add(decimal(num1), decimal(num2))
@doc """
Subtracts second number from the first. Equivalent to `Decimal.add/2` when the
second number's sign is negated.
## Exceptional conditions
* If one number is -Infinity and the other +Infinity `:invalid_operation` will
be signalled.
## Examples
iex> Decimal.sub(1, "0.1")
Decimal.new("0.9")
iex> Decimal.sub(1, "Inf")
Decimal.new("-Infinity")
"""
@spec sub(decimal, decimal) :: t
def sub(%Decimal{} = num1, %Decimal{sign: sign} = num2) do
add(num1, %{num2 | sign: -sign})
end
def sub(num1, num2) do
sub(decimal(num1), decimal(num2))
end
@doc """
Compares two numbers numerically using a threshold. If the first number added
to the threshold is greater than the second number, and the first number
subtracted by the threshold is smaller than the second number, then the two
numbers are considered equal.
## Examples
iex> Decimal.compare("1.1", 1, "0.2")
:eq
iex> Decimal.compare("1.2", 1, "0.1")
:gt
iex> Decimal.compare("1.0", "1.2", "0.1")
:lt
"""
@spec compare(decimal :: decimal(), decimal :: decimal(), threshold :: decimal()) ::
compare_result()
def compare(_, _, %Decimal{sign: -1}), do: raise(Error, reason: "threshold cannot be negative")
def compare(%Decimal{} = n1, %Decimal{} = n2, %Decimal{} = threshold) do
add_threshold = n1 |> Decimal.add(threshold)
sub_threshold = n1 |> Decimal.sub(threshold)
case1 = compare(add_threshold, n2)
case2 = compare(sub_threshold, n2)
cond do
(case1 == :gt or case1 == :eq) and (case2 == :lt or case2 == :eq) -> :eq
case1 == :gt -> :gt
case2 == :lt -> :lt
end
end
def compare(n1, n2, threshold), do: compare(decimal(n1), decimal(n2), decimal(threshold))
@doc """
Compares two numbers numerically. If the first number is greater than the second
`:gt` is returned, if less than `:lt` is returned, if both numbers are equal
`:eq` is returned.
Neither number can be a NaN.
## Examples
iex> Decimal.compare("1.0", 1)
:eq
iex> Decimal.compare("Inf", -1)
:gt
"""
@spec compare(decimal, decimal) :: compare_result()
def compare(%Decimal{coef: :inf, sign: sign}, %Decimal{coef: :inf, sign: sign}),
do: :eq
def compare(%Decimal{coef: :inf, sign: sign1}, %Decimal{coef: :inf, sign: sign2})
when sign1 < sign2,
do: :lt
def compare(%Decimal{coef: :inf, sign: sign1}, %Decimal{coef: :inf, sign: sign2})
when sign1 > sign2,
do: :gt
def compare(%Decimal{coef: :inf, sign: 1}, _num2), do: :gt
def compare(%Decimal{coef: :inf, sign: -1}, _num2), do: :lt
def compare(_num1, %Decimal{coef: :inf, sign: 1}), do: :lt
def compare(_num1, %Decimal{coef: :inf, sign: -1}), do: :gt
def compare(%Decimal{coef: :NaN} = num1, _num2),
do: error(:invalid_operation, "operation on NaN", num1)
def compare(_num1, %Decimal{coef: :NaN} = num2),
do: error(:invalid_operation, "operation on NaN", num2)
def compare(%Decimal{coef: 0}, %Decimal{coef: 0}), do: :eq
def compare(%Decimal{sign: 1}, %Decimal{coef: 0}), do: :gt
def compare(%Decimal{coef: 0}, %Decimal{sign: 1}), do: :lt
def compare(%Decimal{sign: -1}, %Decimal{coef: 0}), do: :lt
def compare(%Decimal{coef: 0}, %Decimal{sign: -1}), do: :gt
def compare(%Decimal{sign: 1}, %Decimal{sign: -1}), do: :gt
def compare(%Decimal{sign: -1}, %Decimal{sign: 1}), do: :lt
# With equal exponents the adjusted exponents differ exactly as the
# coefficient lengths do, so the coefficients decide it on their own and no
# digits need counting.
def compare(%Decimal{sign: sign, coef: coef1, exp: exp}, %Decimal{coef: coef2, exp: exp}) do
cond do
coef1 == coef2 -> :eq
coef1 < coef2 -> if sign == 1, do: :lt, else: :gt
true -> if sign == 1, do: :gt, else: :lt
end
end
def compare(%Decimal{} = num1, %Decimal{} = num2) do
adjusted_exp1 = adjust_exp(num1)
adjusted_exp2 = adjust_exp(num2)
sign =
cond do
adjusted_exp1 == adjusted_exp2 ->
{coef1, coef2} = add_align(num1.coef, num1.exp, num2.coef, num2.exp)
cond do
coef1 == coef2 -> 0
coef1 < coef2 -> -num1.sign
true -> num1.sign
end
adjusted_exp1 < adjusted_exp2 ->
-num1.sign
true ->
num1.sign
end
case sign do
0 -> :eq
1 -> :gt
-1 -> :lt
end
end
def compare(num1, num2) do
compare(decimal(num1), decimal(num2))
end
@compile {:inline, adjust_exp: 1}
defp adjust_exp(%Decimal{coef: coef, exp: exp}) do
coef_adjustment = coef_length(coef)
exp + coef_adjustment - 1
end
# The ladder compares only against literals that fit a machine word
# (2^59 - 1 is the largest), so each rung is a register compare. Bignums
# leave it after two rungs, because comparing them costs an order of
# magnitude more than the bit-length estimate they fall through to.
defp coef_length(coef) when coef < 1_000_000_000 do
cond do
coef < 10 -> 1
coef < 100 -> 2
coef < 1_000 -> 3
coef < 10_000 -> 4
coef < 100_000 -> 5
coef < 1_000_000 -> 6
coef < 10_000_000 -> 7
coef < 100_000_000 -> 8
true -> 9
end
end
defp coef_length(coef) when coef <= 576_460_752_303_423_487 do
cond do
coef < 10_000_000_000 -> 10
coef < 100_000_000_000 -> 11
coef < 1_000_000_000_000 -> 12
coef < 10_000_000_000_000 -> 13
coef < 100_000_000_000_000 -> 14
coef < 1_000_000_000_000_000 -> 15
coef < 10_000_000_000_000_000 -> 16
coef < 100_000_000_000_000_000 -> 17
true -> 18
end
end
# One more rung for the bignums that are still 18 digits: the estimate costs
# about ten comparisons, so this one pays for itself.
defp coef_length(coef) when coef < 1_000_000_000_000_000_000, do: 18
defp coef_length(coef), do: integer_decimal_digit_count(coef)
@deprecated "Use compare/2 instead"
@spec cmp(decimal, decimal) :: :lt | :eq | :gt
def cmp(num1, num2) do
compare(num1, num2)
end
@doc """
Compares two numbers numerically and returns `true` if they are equal,
otherwise `false`. If one of the operands is a quiet NaN this operation
will always return `false`.
## Examples
iex> Decimal.equal?("1.0", 1)
true
iex> Decimal.equal?(1, -1)
false
"""
@spec equal?(decimal, decimal) :: boolean
def equal?(num1, num2) do
eq?(num1, num2)
end
@doc """
Compares two numbers numerically and returns `true` if they are equal,
otherwise `false`. If one of the operands is a quiet NaN this operation
will always return `false`.
## Examples
iex> Decimal.eq?("1.0", 1)
true
iex> Decimal.eq?(1, -1)
false
"""
doc_since("1.8.0")
@spec eq?(decimal, decimal) :: boolean
def eq?(%Decimal{coef: :NaN}, _num2), do: false
def eq?(_num1, %Decimal{coef: :NaN}), do: false
def eq?(num1, num2), do: compare(num1, num2) == :eq
@doc """
It compares the equality of two numbers. If the second number is within
the range of first - threshold and first + threshold, it returns true;
otherwise, it returns false.
## Examples
iex> Decimal.eq?("1.0", 1, "0")
true
iex> Decimal.eq?("1.2", 1, "0.1")
false
iex> Decimal.eq?("1.2", 1, "0.2")
true
iex> Decimal.eq?(1, -1, "0.0")
false
"""
doc_since("2.2.0")
@spec eq?(decimal :: decimal(), decimal :: decimal(), threshold :: decimal()) :: boolean()
def eq?(num1, num2, threshold), do: compare(num1, num2, threshold) == :eq
@doc """
Compares two numbers numerically and returns `true` if the first argument
is greater than the second, otherwise `false`. If one the operands is a
quiet NaN this operation will always return `false`.
## Examples
iex> Decimal.gt?("1.3", "1.2")
true
iex> Decimal.gt?("1.2", "1.3")
false
"""
doc_since("1.8.0")
@spec gt?(decimal, decimal) :: boolean
def gt?(%Decimal{coef: :NaN}, _num2), do: false
def gt?(_num1, %Decimal{coef: :NaN}), do: false
def gt?(num1, num2), do: compare(num1, num2) == :gt
@doc """
Compares two numbers numerically and returns `true` if the first number is
less than the second number, otherwise `false`. If one of the operands is a
quiet NaN this operation will always return `false`.
## Examples
iex> Decimal.lt?("1.1", "1.2")
true
iex> Decimal.lt?("1.4", "1.2")
false
"""
doc_since("1.8.0")
@spec lt?(decimal, decimal) :: boolean
def lt?(%Decimal{coef: :NaN}, _num2), do: false
def lt?(_num1, %Decimal{coef: :NaN}), do: false
def lt?(num1, num2), do: compare(num1, num2) == :lt
@doc """
Compares two numbers numerically and returns `true` if
the first argument is greater than or equal the second,
otherwise `false`.
If one the operands is a quiet NaN this operation
will always return `false`.
## Examples
iex> Decimal.gte?("1.3", "1.3")
true
iex> Decimal.gte?("1.3", "1.2")
true
iex> Decimal.gte?("1.2", "1.3")
false
"""
doc_since("2.2.0")
@spec gte?(decimal, decimal) :: boolean
def gte?(%Decimal{coef: :NaN}, _num2), do: false
def gte?(_num1, %Decimal{coef: :NaN}), do: false
def gte?(num1, num2) do
case compare(num1, num2) do
:gt -> true
:eq -> true
_ -> false
end
end
@doc """
Compares two numbers numerically and returns `true` if
the first number is less than or equal the second number,
otherwise `false`.
If one of the operands is a quiet NaN this operation
will always return `false`.
## Examples
iex> Decimal.lte?("1.1", "1.1")
true
iex> Decimal.lte?("1.1", "1.2")
true
iex> Decimal.lte?("1.4", "1.2")
false
"""
doc_since("2.2.0")
@spec lte?(decimal, decimal) :: boolean
def lte?(%Decimal{coef: :NaN}, _num2), do: false
def lte?(_num1, %Decimal{coef: :NaN}), do: false
def lte?(num1, num2) do
case compare(num1, num2) do
:lt -> true
:eq -> true
_ -> false
end
end
@doc """
Divides two numbers.
## Exceptional conditions
* If both numbers are ±Infinity `:invalid_operation` is signalled.
* If both numbers are ±0 `:invalid_operation` is signalled.
* If second number (denominator) is ±0 `:division_by_zero` is signalled.
## Examples
iex> Decimal.div(3, 4)
Decimal.new("0.75")
iex> Decimal.div("Inf", -1)
Decimal.new("-Infinity")
"""
@spec div(decimal, decimal) :: t
def div(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1
def div(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2
def div(%Decimal{coef: :inf}, %Decimal{coef: :inf}),
do: error(:invalid_operation, "±Infinity / ±Infinity", %Decimal{coef: :NaN})
def div(%Decimal{sign: sign1, coef: :inf} = num1, %Decimal{sign: sign2}) do
sign = if sign1 == sign2, do: 1, else: -1
%{num1 | sign: sign}
end
def div(%Decimal{sign: sign1, exp: exp1}, %Decimal{sign: sign2, coef: :inf, exp: exp2}) do
sign = if sign1 == sign2, do: 1, else: -1
# TODO: Subnormal
# exponent?
%Decimal{sign: sign, coef: 0, exp: exp1 - exp2}
end
def div(%Decimal{coef: 0}, %Decimal{coef: 0}),
do: error(:invalid_operation, "0 / 0", %Decimal{coef: :NaN})
def div(%Decimal{sign: sign1}, %Decimal{sign: sign2, coef: 0}) do
sign = if sign1 == sign2, do: 1, else: -1
error(:division_by_zero, nil, %Decimal{sign: sign, coef: :inf})
end
def div(%Decimal{} = num1, %Decimal{} = num2) do
%Decimal{sign: sign1, coef: coef1, exp: exp1} = num1
%Decimal{sign: sign2, coef: coef2, exp: exp2} = num2
sign = if sign1 == sign2, do: 1, else: -1
if coef1 == 0 do
context(%Decimal{sign: sign, coef: 0, exp: exp1 - exp2}, [])
else
ctx = Context.get()
{coef1, coef2, adjust} = div_adjust(coef1, coef2)
{coef, adjust, rem, signals, digits} = div_calc(coef1, coef2, adjust, ctx.precision)
# `rem` is the leftover of the division below the digits we kept.
# It must be carried into rounding as the sticky bit: a nonzero `rem`
# means the true quotient lies strictly beyond the last computed digit,
# so a guard digit of 5 is not an exact tie (`:half_even`/`:half_down`)
# and a guard digit of 0 is still nonzero for `:ceiling`/`:floor`/`:up`.
# Without it, ~5% of inexact divisions round the wrong way.
context(
%Decimal{sign: sign, coef: coef, exp: exp1 - exp2 - adjust},
signals,
rem != 0,
ctx,
digits
)
end
end
def div(num1, num2) do
div(decimal(num1), decimal(num2))
end
@doc """
Divides two numbers and returns the integer part.
## Exceptional conditions
* If both numbers are ±Infinity `:invalid_operation` is signalled.
* If both numbers are ±0 `:invalid_operation` is signalled.
* If second number (denominator) is ±0 `:division_by_zero` is signalled.
## Examples
iex> Decimal.div_int(5, 2)
Decimal.new("2")
iex> Decimal.div_int("Inf", -1)
Decimal.new("-Infinity")
"""
@spec div_int(decimal, decimal) :: t
def div_int(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1
def div_int(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2
def div_int(%Decimal{coef: :inf}, %Decimal{coef: :inf}),
do: error(:invalid_operation, "±Infinity / ±Infinity", %Decimal{coef: :NaN})
def div_int(%Decimal{sign: sign1, coef: :inf} = num1, %Decimal{sign: sign2}) do
sign = if sign1 == sign2, do: 1, else: -1
%{num1 | sign: sign}
end
def div_int(%Decimal{sign: sign1, exp: exp1}, %Decimal{sign: sign2, coef: :inf, exp: exp2}) do
sign = if sign1 == sign2, do: 1, else: -1
# TODO: Subnormal
# exponent?
%Decimal{sign: sign, coef: 0, exp: exp1 - exp2}
end
def div_int(%Decimal{coef: 0}, %Decimal{coef: 0}),
do: error(:invalid_operation, "0 / 0", %Decimal{coef: :NaN})
def div_int(%Decimal{sign: sign1}, %Decimal{sign: sign2, coef: 0}) do
div_sign = if sign1 == sign2, do: 1, else: -1
error(:division_by_zero, nil, %Decimal{sign: div_sign, coef: :inf})
end
def div_int(%Decimal{} = num1, %Decimal{} = num2) do
%Decimal{sign: sign1, coef: coef1, exp: exp1} = num1
%Decimal{sign: sign2, coef: coef2, exp: exp2} = num2
div_sign = if sign1 == sign2, do: 1, else: -1
cond do
compare(%{num1 | sign: 1}, %{num2 | sign: 1}) == :lt ->
%Decimal{sign: div_sign, coef: 0, exp: exp1 - exp2}
coef1 == 0 ->
context(%{num1 | sign: div_sign})
true ->
case integer_division(div_sign, coef1, exp1, coef2, exp2) do
{:ok, result} ->
result
{:error, error, reason, num} ->
error(error, reason, num)
end
end
end
def div_int(num1, num2) do
div_int(decimal(num1), decimal(num2))
end
@doc """
Remainder of integer division of two numbers. The result will have the sign of
the first number.
## Exceptional conditions
* If both numbers are ±Infinity `:invalid_operation` is signalled.
* If both numbers are ±0 `:invalid_operation` is signalled.
* If second number (denominator) is ±0 `:division_by_zero` is signalled.
## Examples
iex> Decimal.rem(5, 2)
Decimal.new("1")
"""
@spec rem(decimal, decimal) :: t
def rem(%Decimal{coef: :NaN} = num1, %Decimal{}), do: num1
def rem(%Decimal{}, %Decimal{coef: :NaN} = num2), do: num2
def rem(%Decimal{coef: :inf}, %Decimal{coef: :inf}),
do: error(:invalid_operation, "±Infinity / ±Infinity", %Decimal{coef: :NaN})
def rem(%Decimal{sign: sign1, coef: :inf}, %Decimal{}), do: %Decimal{sign: sign1, coef: 0}
def rem(%Decimal{sign: sign1}, %Decimal{coef: :inf} = num2) do
# TODO: Subnormal
# exponent?
%{num2 | sign: sign1}
end
def rem(%Decimal{coef: 0}, %Decimal{coef: 0}),
do: error(:invalid_operation, "0 / 0", %Decimal{coef: :NaN})
def rem(%Decimal{sign: sign1}, %Decimal{coef: 0}),
do: error(:division_by_zero, nil, %Decimal{sign: sign1, coef: 0})
def rem(%Decimal{} = num1, %Decimal{} = num2) do
%Decimal{sign: sign1, coef: coef1, exp: exp1} = num1
%Decimal{sign: sign2, coef: coef2, exp: exp2} = num2
cond do
compare(%{num1 | sign: 1}, %{num2 | sign: 1}) == :lt ->
context(%{num1 | sign: sign1})
coef1 == 0 ->
context(%{num2 | sign: sign1})
true ->
div_sign = if sign1 == sign2, do: 1, else: -1
case integer_division(div_sign, coef1, exp1, coef2, exp2) do
{:ok, result} ->
exact_rem(num1, num2, result)
{:error, error, reason, num} ->
error(error, reason, num)
end
end
end
def rem(num1, num2) do
rem(decimal(num1), decimal(num2))
end
@doc """
Integer division of two numbers and the remainder. Should be used when both