-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
math.jl
1595 lines (1310 loc) · 43.8 KB
/
math.jl
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
# This file is a part of Julia. License is MIT: https://julialang.org/license
module Math
export sin, cos, sincos, tan, sinh, cosh, tanh, asin, acos, atan,
asinh, acosh, atanh, sec, csc, cot, asec, acsc, acot,
sech, csch, coth, asech, acsch, acoth,
sinpi, cospi, sincospi, tanpi, sinc, cosc,
cosd, cotd, cscd, secd, sind, tand, sincosd,
acosd, acotd, acscd, asecd, asind, atand,
rad2deg, deg2rad,
log, log2, log10, log1p, exponent, exp, exp2, exp10, expm1,
cbrt, sqrt, fourthroot, significand,
hypot, max, min, minmax, ldexp, frexp,
clamp, clamp!, modf, ^, mod2pi, rem2pi,
@evalpoly, evalpoly
import .Base: log, exp, sin, cos, tan, sinh, cosh, tanh, asin,
acos, atan, asinh, acosh, atanh, sqrt, log2, log10,
max, min, minmax, ^, exp2, muladd, rem,
exp10, expm1, log1p, @constprop, @assume_effects
using .Base: sign_mask, exponent_mask, exponent_one,
exponent_half, uinttype, significand_mask,
significand_bits, exponent_bits, exponent_bias,
exponent_max, exponent_raw_max, clamp, clamp!
using Core.Intrinsics: sqrt_llvm
using .Base: IEEEFloat
@noinline function throw_complex_domainerror(f::Symbol, x)
throw(DomainError(x,
LazyString(f," was called with a negative real argument but will only return a complex result if called with a complex argument. Try ", f,"(Complex(x)).")))
end
@noinline function throw_complex_domainerror_neg1(f::Symbol, x)
throw(DomainError(x,
LazyString(f," was called with a real argument < -1 but will only return a complex result if called with a complex argument. Try ", f,"(Complex(x)).")))
end
@noinline function throw_exp_domainerror(x)
throw(DomainError(x, LazyString(
"Exponentiation yielding a complex result requires a ",
"complex argument.\nReplace x^y with (x+0im)^y, ",
"Complex(x)^y, or similar.")))
end
# non-type specific math functions
function two_mul(x::T, y::T) where {T<:Number}
xy = x*y
xy, fma(x, y, -xy)
end
@assume_effects :consistent @inline function two_mul(x::Float64, y::Float64)
if Core.Intrinsics.have_fma(Float64)
xy = x*y
return xy, fma(x, y, -xy)
end
return Base.twomul(x,y)
end
@assume_effects :consistent @inline function two_mul(x::T, y::T) where T<: Union{Float16, Float32}
if Core.Intrinsics.have_fma(T)
xy = x*y
return xy, fma(x, y, -xy)
end
xy = widen(x)*y
Txy = T(xy)
return Txy, T(xy-Txy)
end
"""
evalpoly(x, p)
Evaluate the polynomial ``\\sum_k x^{k-1} p[k]`` for the coefficients `p[1]`, `p[2]`, ...;
that is, the coefficients are given in ascending order by power of `x`.
Loops are unrolled at compile time if the number of coefficients is statically known, i.e.
when `p` is a `Tuple`.
This function generates efficient code using Horner's method if `x` is real, or using
a Goertzel-like [^DK62] algorithm if `x` is complex.
[^DK62]: Donald Knuth, Art of Computer Programming, Volume 2: Seminumerical Algorithms, Sec. 4.6.4.
!!! compat "Julia 1.4"
This function requires Julia 1.4 or later.
# Examples
```jldoctest
julia> evalpoly(2, (1, 2, 3))
17
```
"""
function evalpoly(x, p::Tuple)
if @generated
N = length(p.parameters::Core.SimpleVector)
ex = :(p[end])
for i in N-1:-1:1
ex = :(muladd(x, $ex, p[$i]))
end
ex
else
_evalpoly(x, p)
end
end
evalpoly(x, p::AbstractVector) = _evalpoly(x, p)
function _evalpoly(x, p)
Base.require_one_based_indexing(p)
N = length(p)
ex = p[end]
for i in N-1:-1:1
ex = muladd(x, ex, p[i])
end
ex
end
function evalpoly(z::Complex, p::Tuple)
if @generated
N = length(p.parameters)
a = :(p[end])
b = :(p[end-1])
as = []
for i in N-2:-1:1
ai = Symbol("a", i)
push!(as, :($ai = $a))
a = :(muladd(r, $ai, $b))
b = :(muladd(-s, $ai, p[$i]))
end
ai = :a0
push!(as, :($ai = $a))
C = Expr(:block,
:(x = real(z)),
:(y = imag(z)),
:(r = x + x),
:(s = muladd(x, x, y*y)),
as...,
:(muladd($ai, z, $b)))
else
_evalpoly(z, p)
end
end
evalpoly(z::Complex, p::Tuple{<:Any}) = p[1]
evalpoly(z::Complex, p::AbstractVector) = _evalpoly(z, p)
function _evalpoly(z::Complex, p)
Base.require_one_based_indexing(p)
length(p) == 1 && return p[1]
N = length(p)
a = p[end]
b = p[end-1]
x = real(z)
y = imag(z)
r = 2x
s = muladd(x, x, y*y)
for i in N-2:-1:1
ai = a
a = muladd(r, ai, b)
b = muladd(-s, ai, p[i])
end
ai = a
muladd(ai, z, b)
end
"""
@horner(x, p...)
Evaluate `p[1] + x * (p[2] + x * (....))`, i.e. a polynomial via Horner's rule.
See also [`@evalpoly`](@ref), [`evalpoly`](@ref).
"""
macro horner(x, p...)
xesc, pesc = esc(x), esc.(p)
:(invoke(evalpoly, Tuple{Any, Tuple}, $xesc, ($(pesc...),)))
end
# Evaluate p[1] + z*p[2] + z^2*p[3] + ... + z^(n-1)*p[n]. This uses
# Horner's method if z is real, but for complex z it uses a more
# efficient algorithm described in Knuth, TAOCP vol. 2, section 4.6.4,
# equation (3).
"""
@evalpoly(z, c...)
Evaluate the polynomial ``\\sum_k z^{k-1} c[k]`` for the coefficients `c[1]`, `c[2]`, ...;
that is, the coefficients are given in ascending order by power of `z`. This macro expands
to efficient inline code that uses either Horner's method or, for complex `z`, a more
efficient Goertzel-like algorithm.
See also [`evalpoly`](@ref).
# Examples
```jldoctest
julia> @evalpoly(3, 1, 0, 1)
10
julia> @evalpoly(2, 1, 0, 1)
5
julia> @evalpoly(2, 1, 1, 1)
7
```
"""
macro evalpoly(z, p...)
zesc, pesc = esc(z), esc.(p)
:(evalpoly($zesc, ($(pesc...),)))
end
# polynomial evaluation using compensated summation.
# much more accurate, especially when lo can be combined with other rounding errors
@inline function exthorner(x::T, p::Tuple{T,T,T}) where T<:Union{Float32,Float64}
hi, lo = p[lastindex(p)], zero(x)
hi, lo = _exthorner(2, x, p, hi, lo)
hi, lo = _exthorner(1, x, p, hi, lo)
return hi, lo
end
@inline function _exthorner(i::Int, x::T, p::Tuple{T,T,T}, hi::T, lo::T) where T<:Union{Float32,Float64}
i == 2 || i == 1 || error("unexpected index")
pi = p[i]
prod, err = two_mul(hi,x)
hi = pi+prod
lo = fma(lo, x, prod - (hi - pi) + err)
return hi, lo
end
"""
rad2deg(x)
Convert `x` from radians to degrees.
See also [`deg2rad`](@ref).
# Examples
```jldoctest
julia> rad2deg(pi)
180.0
```
"""
rad2deg(z::AbstractFloat) = z * (180 / oftype(z, pi))
"""
deg2rad(x)
Convert `x` from degrees to radians.
See also [`rad2deg`](@ref), [`sind`](@ref), [`pi`](@ref).
# Examples
```jldoctest
julia> deg2rad(90)
1.5707963267948966
```
"""
deg2rad(z::AbstractFloat) = z * (oftype(z, pi) / 180)
rad2deg(z::Real) = rad2deg(float(z))
deg2rad(z::Real) = deg2rad(float(z))
rad2deg(z::Number) = (z/pi)*180
deg2rad(z::Number) = (z*pi)/180
log(b::T, x::T) where {T<:Number} = log(x)/log(b)
"""
log(b,x)
Compute the base `b` logarithm of `x`. Throw a [`DomainError`](@ref) for negative
[`Real`](@ref) arguments.
# Examples
```jldoctest; filter = r"Stacktrace:(\\n \\[[0-9]+\\].*)*"
julia> log(4,8)
1.5
julia> log(4,2)
0.5
julia> log(-2, 3)
ERROR: DomainError with -2.0:
log was called with a negative real argument but will only return a complex result if called with a complex argument. Try log(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31
[...]
julia> log(2, -3)
ERROR: DomainError with -3.0:
log was called with a negative real argument but will only return a complex result if called with a complex argument. Try log(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31
[...]
```
!!! note
If `b` is a power of 2 or 10, [`log2`](@ref) or [`log10`](@ref) should be used, as these will
typically be faster and more accurate. For example,
```jldoctest
julia> log(100,1000000)
2.9999999999999996
julia> log10(1000000)/2
3.0
```
"""
log(b::Number, x::Number) = log(promote(b,x)...)
# type specific math functions
const libm = Base.libm_name
# functions with no domain error
"""
sinh(x)
Compute hyperbolic sine of `x`.
See also [`sin`](@ref).
"""
sinh(x::Number)
"""
cosh(x)
Compute hyperbolic cosine of `x`.
See also [`cos`](@ref).
"""
cosh(x::Number)
"""
tanh(x)
Compute hyperbolic tangent of `x`.
See also [`tan`](@ref), [`atanh`](@ref).
# Examples
```jldoctest
julia> tanh.(-3:3f0) # Here 3f0 isa Float32
7-element Vector{Float32}:
-0.9950548
-0.9640276
-0.7615942
0.0
0.7615942
0.9640276
0.9950548
julia> tan.(im .* (1:3))
3-element Vector{ComplexF64}:
0.0 + 0.7615941559557649im
0.0 + 0.9640275800758169im
0.0 + 0.9950547536867306im
```
"""
tanh(x::Number)
"""
atan(y)
atan(y, x)
Compute the inverse tangent of `y` or `y/x`, respectively.
For one real argument, this is the angle in radians between the positive *x*-axis and the point
(1, *y*), returning a value in the interval ``[-\\pi/2, \\pi/2]``.
For two arguments, this is the angle in radians between the positive *x*-axis and the
point (*x*, *y*), returning a value in the interval ``[-\\pi, \\pi]``. This corresponds to a
standard [`atan2`](https://en.wikipedia.org/wiki/Atan2) function. Note that by convention
`atan(0.0,x)` is defined as ``\\pi`` and `atan(-0.0,x)` is defined as ``-\\pi`` when `x < 0`.
See also [`atand`](@ref) for degrees.
# Examples
```jldoctest
julia> rad2deg(atan(-1/√3))
-30.000000000000004
julia> rad2deg(atan(-1, √3))
-30.000000000000004
julia> rad2deg(atan(1, -√3))
150.0
```
"""
atan(x::Number)
"""
asinh(x)
Compute the inverse hyperbolic sine of `x`.
"""
asinh(x::Number)
# utility for converting NaN return to DomainError
# the branch in nan_dom_err prevents its callers from inlining, so be sure to force it
# until the heuristics can be improved
@inline nan_dom_err(out, x) = isnan(out) & !isnan(x) ? throw(DomainError(x, "NaN result for non-NaN input.")) : out
# functions that return NaN on non-NaN argument for domain error
"""
sin(x::T) where {T <: Number} -> float(T)
Compute sine of `x`, where `x` is in radians.
Throw a [`DomainError`](@ref) if `isinf(x)`, return a `T(NaN)` if `isnan(x)`.
See also [`sind`](@ref), [`sinpi`](@ref), [`sincos`](@ref), [`cis`](@ref), [`asin`](@ref).
# Examples
```jldoctest
julia> round.(sin.(range(0, 2pi, length=9)'), digits=3)
1×9 Matrix{Float64}:
0.0 0.707 1.0 0.707 0.0 -0.707 -1.0 -0.707 -0.0
julia> sind(45)
0.7071067811865476
julia> sinpi(1/4)
0.7071067811865475
julia> round.(sincos(pi/6), digits=3)
(0.5, 0.866)
julia> round(cis(pi/6), digits=3)
0.866 + 0.5im
julia> round(exp(im*pi/6), digits=3)
0.866 + 0.5im
```
"""
sin(x::Number)
"""
cos(x::T) where {T <: Number} -> float(T)
Compute cosine of `x`, where `x` is in radians.
Throw a [`DomainError`](@ref) if `isinf(x)`, return a `T(NaN)` if `isnan(x)`.
See also [`cosd`](@ref), [`cospi`](@ref), [`sincos`](@ref), [`cis`](@ref).
"""
cos(x::Number)
"""
tan(x::T) where {T <: Number} -> float(T)
Compute tangent of `x`, where `x` is in radians.
Throw a [`DomainError`](@ref) if `isinf(x)`, return a `T(NaN)` if `isnan(x)`.
See also [`tanh`](@ref).
"""
tan(x::Number)
"""
asin(x::T) where {T <: Number} -> float(T)
Compute the inverse sine of `x`, where the output is in radians.
Return a `T(NaN)` if `isnan(x)`.
See also [`asind`](@ref) for output in degrees.
# Examples
```jldoctest
julia> asin.((0, 1/2, 1))
(0.0, 0.5235987755982989, 1.5707963267948966)
julia> asind.((0, 1/2, 1))
(0.0, 30.000000000000004, 90.0)
```
"""
asin(x::Number)
"""
acos(x::T) where {T <: Number} -> float(T)
Compute the inverse cosine of `x`, where the output is in radians
Return a `T(NaN)` if `isnan(x)`.
"""
acos(x::Number)
"""
acosh(x)
Compute the inverse hyperbolic cosine of `x`.
"""
acosh(x::Number)
"""
atanh(x)
Compute the inverse hyperbolic tangent of `x`.
"""
atanh(x::Number)
"""
log(x)
Compute the natural logarithm of `x`.
Throw a [`DomainError`](@ref) for negative [`Real`](@ref) arguments.
Use [`Complex`](@ref) arguments to obtain [`Complex`](@ref) results.
!!! note "Branch cut"
`log` has a branch cut along the negative real axis; `-0.0im` is taken
to be below the axis.
See also [`ℯ`](@ref), [`log1p`](@ref), [`log2`](@ref), [`log10`](@ref).
# Examples
```jldoctest; filter = r"Stacktrace:(\\n \\[[0-9]+\\].*)*"
julia> log(2)
0.6931471805599453
julia> log(-3)
ERROR: DomainError with -3.0:
log was called with a negative real argument but will only return a complex result if called with a complex argument. Try log(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31
[...]
julia> log(-3 + 0im)
1.0986122886681098 + 3.141592653589793im
julia> log(-3 - 0.0im)
1.0986122886681098 - 3.141592653589793im
julia> log.(exp.(-1:1))
3-element Vector{Float64}:
-1.0
0.0
1.0
```
"""
log(x::Number)
"""
log2(x)
Compute the logarithm of `x` to base 2. Throw a [`DomainError`](@ref) for negative
[`Real`](@ref) arguments.
See also: [`exp2`](@ref), [`ldexp`](@ref), [`ispow2`](@ref).
# Examples
```jldoctest; filter = r"Stacktrace:(\\n \\[[0-9]+\\].*)*"
julia> log2(4)
2.0
julia> log2(10)
3.321928094887362
julia> log2(-2)
ERROR: DomainError with -2.0:
log2 was called with a negative real argument but will only return a complex result if called with a complex argument. Try log2(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(f::Symbol, x::Float64) at ./math.jl:31
[...]
julia> log2.(2.0 .^ (-1:1))
3-element Vector{Float64}:
-1.0
0.0
1.0
```
"""
log2(x)
"""
log10(x)
Compute the logarithm of `x` to base 10.
Throw a [`DomainError`](@ref) for negative [`Real`](@ref) arguments.
# Examples
```jldoctest; filter = r"Stacktrace:(\\n \\[[0-9]+\\].*)*"
julia> log10(100)
2.0
julia> log10(2)
0.3010299956639812
julia> log10(-2)
ERROR: DomainError with -2.0:
log10 was called with a negative real argument but will only return a complex result if called with a complex argument. Try log10(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(f::Symbol, x::Float64) at ./math.jl:31
[...]
```
"""
log10(x)
"""
log1p(x)
Accurate natural logarithm of `1+x`. Throw a [`DomainError`](@ref) for [`Real`](@ref)
arguments less than -1.
# Examples
```jldoctest; filter = r"Stacktrace:(\\n \\[[0-9]+\\].*)*"
julia> log1p(-0.5)
-0.6931471805599453
julia> log1p(0)
0.0
julia> log1p(-2)
ERROR: DomainError with -2.0:
log1p was called with a real argument < -1 but will only return a complex result if called with a complex argument. Try log1p(Complex(x)).
Stacktrace:
[1] throw_complex_domainerror(::Symbol, ::Float64) at ./math.jl:31
[...]
```
"""
log1p(x)
@inline function sqrt(x::Union{Float32,Float64})
x < zero(x) && throw_complex_domainerror(:sqrt, x)
sqrt_llvm(x)
end
"""
sqrt(x)
Return ``\\sqrt{x}``.
Throw a [`DomainError`](@ref) for negative [`Real`](@ref) arguments.
Use [`Complex`](@ref) negative arguments instead to obtain a [`Complex`](@ref) result.
The prefix operator `√` is equivalent to `sqrt`.
!!! note "Branch cut"
`sqrt` has a branch cut along the negative real axis; `-0.0im` is taken
to be below the axis.
See also: [`hypot`](@ref).
# Examples
```jldoctest; filter = r"Stacktrace:(\\n \\[[0-9]+\\].*)*"
julia> sqrt(big(81))
9.0
julia> sqrt(big(-81))
ERROR: DomainError with -81.0:
NaN result for non-NaN input.
Stacktrace:
[1] sqrt(::BigFloat) at ./mpfr.jl:501
[...]
julia> sqrt(big(complex(-81)))
0.0 + 9.0im
julia> sqrt(-81 - 0.0im) # -0.0im is below the branch cut
0.0 - 9.0im
julia> .√(1:4)
4-element Vector{Float64}:
1.0
1.4142135623730951
1.7320508075688772
2.0
```
"""
sqrt(x)
"""
fourthroot(x)
Return the fourth root of `x` by applying `sqrt` twice successively.
"""
fourthroot(x::Number) = sqrt(sqrt(x))
"""
hypot(x, y)
Compute the hypotenuse ``\\sqrt{|x|^2+|y|^2}`` avoiding overflow and underflow.
This code is an implementation of the algorithm described in:
An Improved Algorithm for `hypot(a,b)`
by Carlos F. Borges
The article is available online at arXiv at the link
https://arxiv.org/abs/1904.09481
hypot(x...)
Compute the hypotenuse ``\\sqrt{\\sum |x_i|^2}`` avoiding overflow and underflow.
See also `norm` in the [`LinearAlgebra`](@ref man-linalg) standard library.
# Examples
```jldoctest; filter = r"Stacktrace:(\\n \\[[0-9]+\\].*)*"
julia> a = Int64(10)^10;
julia> hypot(a, a)
1.4142135623730951e10
julia> √(a^2 + a^2) # a^2 overflows
ERROR: DomainError with -2.914184810805068e18:
sqrt was called with a negative real argument but will only return a complex result if called with a complex argument. Try sqrt(Complex(x)).
Stacktrace:
[...]
julia> hypot(3, 4im)
5.0
julia> hypot(-5.7)
5.7
julia> hypot(3, 4im, 12.0)
13.0
julia> using LinearAlgebra
julia> norm([a, a, a, a]) == hypot(a, a, a, a)
true
```
"""
hypot(x::Number) = abs(float(x))
hypot(x::Number, y::Number) = _hypot(float.(promote(x, y))...)
hypot(x::Number, y::Number, xs::Number...) = _hypot(float.(promote(x, y, xs...)))
function _hypot(x, y)
# preserves unit
axu = abs(x)
ayu = abs(y)
# unitless
ax = axu / oneunit(axu)
ay = ayu / oneunit(ayu)
# Return Inf if either or both inputs is Inf (Compliance with IEEE754)
if isinf(ax) || isinf(ay)
return typeof(axu)(Inf)
end
# Order the operands
if ay > ax
axu, ayu = ayu, axu
ax, ay = ay, ax
end
# Widely varying operands
if ay <= ax*sqrt(eps(typeof(ax))/2) #Note: This also gets ay == 0
return axu
end
# Operands do not vary widely
scale = eps(typeof(ax))*sqrt(floatmin(ax)) #Rescaling constant
if ax > sqrt(floatmax(ax)/2)
ax = ax*scale
ay = ay*scale
scale = inv(scale)
elseif ay < sqrt(floatmin(ax))
ax = ax/scale
ay = ay/scale
else
scale = oneunit(scale)
end
h = sqrt(muladd(ax, ax, ay*ay))
# This branch is correctly rounded but requires a native hardware fma.
if Core.Intrinsics.have_fma(typeof(h))
hsquared = h*h
axsquared = ax*ax
h -= (fma(-ay, ay, hsquared-axsquared) + fma(h, h,-hsquared) - fma(ax, ax, -axsquared))/(2*h)
# This branch is within one ulp of correctly rounded.
else
if h <= 2*ay
delta = h-ay
h -= muladd(delta, delta-2*(ax-ay), ax*(2*delta - ax))/(2*h)
else
delta = h-ax
h -= muladd(delta, delta, muladd(ay, (4*delta - ay), 2*delta*(ax - 2*ay)))/(2*h)
end
end
return h*scale*oneunit(axu)
end
@inline function _hypot(x::Float32, y::Float32)
if isinf(x) || isinf(y)
return Inf32
end
_x, _y = Float64(x), Float64(y)
return Float32(sqrt(muladd(_x, _x, _y*_y)))
end
@inline function _hypot(x::Float16, y::Float16)
if isinf(x) || isinf(y)
return Inf16
end
_x, _y = Float32(x), Float32(y)
return Float16(sqrt(muladd(_x, _x, _y*_y)))
end
_hypot(x::ComplexF16, y::ComplexF16) = Float16(_hypot(ComplexF32(x), ComplexF32(y)))
function _hypot(x::NTuple{N,<:Number}) where {N}
maxabs = maximum(abs, x)
if isnan(maxabs) && any(isinf, x)
return typeof(maxabs)(Inf)
elseif (iszero(maxabs) || isinf(maxabs))
return maxabs
else
return maxabs * sqrt(sum(y -> abs2(y / maxabs), x))
end
end
function _hypot(x::NTuple{N,<:IEEEFloat}) where {N}
T = eltype(x)
infT = convert(T, Inf)
x = abs.(x) # doesn't change result but enables computational shortcuts
# note: any() was causing this to not inline for N=3 but mapreduce() was not
mapreduce(==(infT), |, x) && return infT # return Inf even if an argument is NaN
maxabs = reinterpret(T, maximum(z -> reinterpret(Signed, z), x)) # for abs(::IEEEFloat) values, a ::BitInteger cast does not change the result
maxabs > zero(T) || return maxabs # catch NaN before the @fastmath below, but also shortcut 0 since we can (remove if no more @fastmath below)
scale,invscale = scaleinv(maxabs)
# @fastmath(+) to allow reassociation (see #48129)
add_fast(x, y) = Core.Intrinsics.add_float_fast(x, y) # @fastmath is not available during bootstrap
return scale * sqrt(mapreduce(y -> abs2(y * invscale), add_fast, x))
end
atan(y::Real, x::Real) = atan(promote(float(y),float(x))...)
atan(y::T, x::T) where {T<:AbstractFloat} = Base.no_op_err("atan", T)
_isless(x::T, y::T) where {T<:AbstractFloat} = (x < y) || (signbit(x) > signbit(y))
min(x::T, y::T) where {T<:AbstractFloat} = isnan(x) || ~isnan(y) && _isless(x, y) ? x : y
max(x::T, y::T) where {T<:AbstractFloat} = isnan(x) || ~isnan(y) && _isless(y, x) ? x : y
minmax(x::T, y::T) where {T<:AbstractFloat} = min(x, y), max(x, y)
_isless(x::Float16, y::Float16) = signbit(widen(x) - widen(y))
const has_native_fminmax = Sys.ARCH === :aarch64
@static if has_native_fminmax
@eval begin
Base.@assume_effects :total @inline llvm_min(x::Float64, y::Float64) = ccall("llvm.minimum.f64", llvmcall, Float64, (Float64, Float64), x, y)
Base.@assume_effects :total @inline llvm_min(x::Float32, y::Float32) = ccall("llvm.minimum.f32", llvmcall, Float32, (Float32, Float32), x, y)
Base.@assume_effects :total @inline llvm_max(x::Float64, y::Float64) = ccall("llvm.maximum.f64", llvmcall, Float64, (Float64, Float64), x, y)
Base.@assume_effects :total @inline llvm_max(x::Float32, y::Float32) = ccall("llvm.maximum.f32", llvmcall, Float32, (Float32, Float32), x, y)
end
end
function min(x::T, y::T) where {T<:Union{Float32,Float64}}
@static if has_native_fminmax
return llvm_min(x,y)
end
diff = x - y
argmin = ifelse(signbit(diff), x, y)
anynan = isnan(x)|isnan(y)
return ifelse(anynan, diff, argmin)
end
function max(x::T, y::T) where {T<:Union{Float32,Float64}}
@static if has_native_fminmax
return llvm_max(x,y)
end
diff = x - y
argmax = ifelse(signbit(diff), y, x)
anynan = isnan(x)|isnan(y)
return ifelse(anynan, diff, argmax)
end
function minmax(x::T, y::T) where {T<:Union{Float32,Float64}}
@static if has_native_fminmax
return llvm_min(x, y), llvm_max(x, y)
end
diff = x - y
sdiff = signbit(diff)
min, max = ifelse(sdiff, x, y), ifelse(sdiff, y, x)
anynan = isnan(x)|isnan(y)
return ifelse(anynan, diff, min), ifelse(anynan, diff, max)
end
"""
ldexp(x, n)
Compute ``x \\times 2^n``.
See also [`frexp`](@ref), [`exponent`](@ref).
# Examples
```jldoctest
julia> ldexp(5.0, 2)
20.0
```
"""
function ldexp(x::T, e::Integer) where T<:IEEEFloat
xu = reinterpret(Unsigned, x)
xs = xu & ~sign_mask(T)
xs >= exponent_mask(T) && return x # NaN or Inf
k = (xs >> significand_bits(T)) % Int
if k == 0 # x is subnormal
xs == 0 && return x # +-0
m = leading_zeros(xs) - exponent_bits(T)
ys = xs << unsigned(m)
xu = ys | (xu & sign_mask(T))
k = 1 - m
# underflow, otherwise may have integer underflow in the following n + k
e < -50000 && return flipsign(T(0.0), x)
end
# For cases where e of an Integer larger than Int make sure we properly
# overflow/underflow; this is optimized away otherwise.
if e > typemax(Int)
return flipsign(T(Inf), x)
elseif e < typemin(Int)
return flipsign(T(0.0), x)
end
n = e % Int
k += n
# overflow, if k is larger than maximum possible exponent
if k >= exponent_raw_max(T)
return flipsign(T(Inf), x)
end
if k > 0 # normal case
xu = (xu & ~exponent_mask(T)) | (rem(k, uinttype(T)) << significand_bits(T))
return reinterpret(T, xu)
else # subnormal case
if k <= -significand_bits(T) # underflow
# overflow, for the case of integer overflow in n + k
e > 50000 && return flipsign(T(Inf), x)
return flipsign(T(0.0), x)
end
k += significand_bits(T)
# z = T(2.0) ^ (-significand_bits(T))
z = reinterpret(T, rem(exponent_bias(T)-significand_bits(T), uinttype(T)) << significand_bits(T))
xu = (xu & ~exponent_mask(T)) | (rem(k, uinttype(T)) << significand_bits(T))
return z*reinterpret(T, xu)
end
end
ldexp(x::Float16, q::Integer) = Float16(ldexp(Float32(x), q))
"""
exponent(x::Real) -> Int
Return the largest integer `y` such that `2^y ≤ abs(x)`.
For a normalized floating-point number `x`, this corresponds to the exponent of `x`.
Throws a `DomainError` when `x` is zero, infinite, or [`NaN`](@ref).
For any other non-subnormal floating-point number `x`, this corresponds to the exponent bits of `x`.
See also [`signbit`](@ref), [`significand`](@ref), [`frexp`](@ref), [`issubnormal`](@ref), [`log2`](@ref), [`ldexp`](@ref).
# Examples
```jldoctest
julia> exponent(8)
3
julia> exponent(6.5)
2
julia> exponent(-1//4)
-2
julia> exponent(3.142e-4)
-12
julia> exponent(floatmin(Float32)), exponent(nextfloat(0.0f0))
(-126, -149)
julia> exponent(0.0)
ERROR: DomainError with 0.0:
Cannot be ±0.0.
[...]
```
"""
function exponent(x::T) where T<:IEEEFloat
@noinline throw1(x) = throw(DomainError(x, "Cannot be NaN or Inf."))
@noinline throw2(x) = throw(DomainError(x, "Cannot be ±0.0."))
xs = reinterpret(Unsigned, x) & ~sign_mask(T)
xs >= exponent_mask(T) && throw1(x)
k = Int(xs >> significand_bits(T))
if k == 0 # x is subnormal
xs == 0 && throw2(x)
m = leading_zeros(xs) - exponent_bits(T)
k = 1 - m
end
return k - exponent_bias(T)
end
# Like exponent, but assumes the nothrow precondition. For
# internal use only. Could be written as
# @assume_effects :nothrow exponent()
# but currently this form is easier on the compiler.
function _exponent_finite_nonzero(x::T) where T<:IEEEFloat
# @precond :nothrow !isnan(x) && !isinf(x) && !iszero(x)
xs = reinterpret(Unsigned, x) & ~sign_mask(T)
k = rem(xs >> significand_bits(T), Int)
if k == 0 # x is subnormal
m = leading_zeros(xs) - exponent_bits(T)
k = 1 - m
end
return k - exponent_bias(T)
end
"""
significand(x)
Extract the significand (a.k.a. mantissa) of a floating-point number. If `x` is