-
-
Notifications
You must be signed in to change notification settings - Fork 405
/
other.py
2126 lines (1677 loc) · 59.3 KB
/
other.py
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
"""
Other functions
"""
from sage.symbolic.function import GinacFunction, BuiltinFunction
from sage.symbolic.expression import Expression
from sage.symbolic.pynac import register_symbol, symbol_table
from sage.symbolic.pynac import py_factorial_py
from sage.symbolic.all import SR
from sage.rings.all import Integer, Rational, RealField, RR, ZZ, ComplexField
from sage.rings.complex_number import is_ComplexNumber
from sage.misc.latex import latex
import math
import sage.structure.element
coercion_model = sage.structure.element.get_coercion_model()
# avoid name conflicts with `parent` as a function parameter
from sage.structure.coerce import parent as s_parent
from sage.symbolic.constants import pi
from sage.symbolic.function import is_inexact
from sage.functions.log import exp
from sage.functions.trig import arctan2
from sage.functions.exp_integral import Ei
from sage.libs.mpmath import utils as mpmath_utils
one_half = ~SR(2)
class Function_erf(BuiltinFunction):
r"""
The error function, defined for real values as
`\text{erf}(x) = \frac{2}{\sqrt{\pi}} \int_0^x e^{-t^2} dt`.
This function is also defined for complex values, via analytic
continuation.
EXAMPLES:
We can evaluate numerically::
sage: erf(2)
erf(2)
sage: erf(2).n()
0.995322265018953
sage: erf(2).n(100)
0.99532226501895273416206925637
sage: erf(ComplexField(100)(2+3j))
-20.829461427614568389103088452 + 8.6873182714701631444280787545*I
Basic symbolic properties are handled by Sage and Maxima::
sage: x = var("x")
sage: diff(erf(x),x)
2*e^(-x^2)/sqrt(pi)
sage: integrate(erf(x),x)
x*erf(x) + e^(-x^2)/sqrt(pi)
ALGORITHM:
Sage implements numerical evaluation of the error function via the
``erf()`` function from mpmath. Symbolics are handled by Sage and Maxima.
REFERENCES:
- http://en.wikipedia.org/wiki/Error_function
- http://mpmath.googlecode.com/svn/trunk/doc/build/functions/expintegrals.html#error-functions
TESTS:
Check limits::
sage: limit(erf(x),x=0)
0
sage: limit(erf(x),x=infinity)
1
Check that it's odd::
sage: erf(1.0)
0.842700792949715
sage: erf(-1.0)
-0.842700792949715
Check against other implementations and against the definition::
sage: erf(3).n()
0.999977909503001
sage: maxima.erf(3).n()
0.999977909503001
sage: (1-pari(3).erfc())
0.999977909503001
sage: RR(3).erf()
0.999977909503001
sage: (integrate(exp(-x**2),(x,0,3))*2/sqrt(pi)).n()
0.999977909503001
:trac:`9044`::
sage: N(erf(sqrt(2)),200)
0.95449973610364158559943472566693312505644755259664313203267
:trac:`11626`::
sage: n(erf(2),100)
0.99532226501895273416206925637
sage: erf(2).n(100)
0.99532226501895273416206925637
Test (indirectly) :trac:`11885`::
sage: erf(float(0.5))
0.5204998778130465
sage: erf(complex(0.5))
(0.5204998778130465+0j)
Ensure conversion from maxima elements works::
sage: merf = maxima(erf(x)).sage().operator()
sage: merf == erf
True
Make sure we can dump and load it::
sage: loads(dumps(erf(2)))
erf(2)
Special-case 0 for immediate evaluation::
sage: erf(0)
0
sage: solve(erf(x)==0,x)
[x == 0]
Make sure that we can hold::
sage: erf(0,hold=True)
erf(0)
sage: simplify(erf(0,hold=True))
0
Check that high-precision ComplexField inputs work::
sage: CC(erf(ComplexField(1000)(2+3j)))
-20.8294614276146 + 8.68731827147016*I
"""
def __init__(self):
r"""
See docstring for :meth:`Function_erf`.
EXAMPLES::
sage: erf(2)
erf(2)
"""
BuiltinFunction.__init__(self, "erf", latex_name=r"\text{erf}")
def _eval_(self, x):
"""
EXAMPLES:
Input is not an expression but is exact::
sage: erf(0)
0
sage: erf(1)
erf(1)
Input is not an expression and is not exact::
sage: erf(0.0)
0.000000000000000
Input is an expression but not a trivial zero::
sage: erf(x)
erf(x)
Input is an expression which is trivially zero::
sage: erf(SR(0))
0
"""
if not isinstance(x, Expression):
if is_inexact(x):
return self._evalf_(x, parent=s_parent(x))
elif x == Integer(0):
return Integer(0)
elif x.is_trivial_zero():
return x
return None
def _evalf_(self, x, parent=None, algorithm=None):
"""
EXAMPLES::
sage: erf(2).n()
0.995322265018953
sage: erf(2).n(200)
0.99532226501895273416206925636725292861089179704006007673835
sage: erf(pi - 1/2*I).n(100)
1.0000111669099367825726058952 + 1.6332655417638522934072124547e-6*I
TESTS:
Check that PARI/GP through the GP interface gives the same answer::
sage: gp.set_real_precision(59) # random
38
sage: print gp.eval("1 - erfc(1)"); print erf(1).n(200);
0.84270079294971486934122063508260925929606699796630290845994
0.84270079294971486934122063508260925929606699796630290845994
Check that for an imaginary input, the output is also imaginary, see
:trac:`13193`::
sage: erf(3.0*I)
1629.99462260157*I
sage: erf(33.0*I)
1.51286977510409e471*I
"""
R = parent or s_parent(x)
import mpmath
return mpmath_utils.call(mpmath.erf, x, parent=R)
def _derivative_(self, x, diff_param=None):
"""
Derivative of erf function
EXAMPLES::
sage: erf(x).diff(x)
2*e^(-x^2)/sqrt(pi)
TESTS:
Check if #8568 is fixed::
sage: var('c,x')
(c, x)
sage: derivative(erf(c*x),x)
2*c*e^(-c^2*x^2)/sqrt(pi)
sage: erf(c*x).diff(x)._maxima_init_()
'((%pi)^(-1/2))*(_SAGE_VAR_c)*(exp(((_SAGE_VAR_c)^(2))*((_SAGE_VAR_x)^(2))*(-1)))*(2)'
"""
return 2*exp(-x**2)/sqrt(pi)
erf = Function_erf()
class Function_abs(GinacFunction):
def __init__(self):
r"""
The absolute value function.
EXAMPLES::
sage: var('x y')
(x, y)
sage: abs(x)
abs(x)
sage: abs(x^2 + y^2)
abs(x^2 + y^2)
sage: abs(-2)
2
sage: sqrt(x^2)
sqrt(x^2)
sage: abs(sqrt(x))
abs(sqrt(x))
sage: complex(abs(3*I))
(3+0j)
sage: f = sage.functions.other.Function_abs()
sage: latex(f)
\mathrm{abs}
sage: latex(abs(x))
{\left| x \right|}
Test pickling::
sage: loads(dumps(abs(x)))
abs(x)
"""
GinacFunction.__init__(self, "abs", latex_name=r"\mathrm{abs}")
abs = abs_symbolic = Function_abs()
class Function_ceil(BuiltinFunction):
def __init__(self):
r"""
The ceiling function.
The ceiling of `x` is computed in the following manner.
#. The ``x.ceil()`` method is called and returned if it
is there. If it is not, then Sage checks if `x` is one of
Python's native numeric data types. If so, then it calls and
returns ``Integer(int(math.ceil(x)))``.
#. Sage tries to convert `x` into a
``RealIntervalField`` with 53 bits of precision. Next,
the ceilings of the endpoints are computed. If they are the same,
then that value is returned. Otherwise, the precision of the
``RealIntervalField`` is increased until they do match
up or it reaches ``maximum_bits`` of precision.
#. If none of the above work, Sage returns a
``Expression`` object.
EXAMPLES::
sage: a = ceil(2/5 + x)
sage: a
ceil(x + 2/5)
sage: a(x=4)
5
sage: a(x=4.0)
5
sage: ZZ(a(x=3))
4
sage: a = ceil(x^3 + x + 5/2); a
ceil(x^3 + x + 5/2)
sage: a.simplify()
ceil(x^3 + x + 1/2) + 2
sage: a(x=2)
13
::
sage: ceil(sin(8)/sin(2))
2
::
sage: ceil(5.4)
6
sage: type(ceil(5.4))
<type 'sage.rings.integer.Integer'>
::
sage: ceil(factorial(50)/exp(1))
11188719610782480504630258070757734324011354208865721592720336801
sage: ceil(SR(10^50 + 10^(-50)))
100000000000000000000000000000000000000000000000001
sage: ceil(SR(10^50 - 10^(-50)))
100000000000000000000000000000000000000000000000000
sage: ceil(sec(e))
-1
sage: latex(ceil(x))
\left \lceil x \right \rceil
::
sage: import numpy
sage: a = numpy.linspace(0,2,6)
sage: ceil(a)
array([ 0., 1., 1., 2., 2., 2.])
Test pickling::
sage: loads(dumps(ceil))
ceil
"""
BuiltinFunction.__init__(self, "ceil",
conversions=dict(maxima='ceiling'))
def _print_latex_(self, x):
r"""
EXAMPLES::
sage: latex(ceil(x)) # indirect doctest
\left \lceil x \right \rceil
"""
return r"\left \lceil %s \right \rceil"%latex(x)
#FIXME: this should be moved to _eval_
def __call__(self, x, maximum_bits=20000):
"""
Allows an object of this class to behave like a function. If
``ceil`` is an instance of this class, we can do ``ceil(n)`` to get
the ceiling of ``n``.
TESTS::
sage: ceil(SR(10^50 + 10^(-50)))
100000000000000000000000000000000000000000000000001
sage: ceil(SR(10^50 - 10^(-50)))
100000000000000000000000000000000000000000000000000
sage: ceil(int(10^50))
100000000000000000000000000000000000000000000000000
"""
try:
return x.ceil()
except AttributeError:
if isinstance(x, (int, long)):
return Integer(x)
elif isinstance(x, (float, complex)):
return Integer(int(math.ceil(x)))
elif type(x).__module__ == 'numpy':
import numpy
return numpy.ceil(x)
x_original = x
from sage.rings.all import RealIntervalField
# If x can be coerced into a real interval, then we should
# try increasing the number of bits of precision until
# we get the ceiling at each of the endpoints is the same.
# The precision will continue to be increased up to maximum_bits
# of precision at which point it will raise a value error.
bits = 53
try:
x_interval = RealIntervalField(bits)(x)
upper_ceil = x_interval.upper().ceil()
lower_ceil = x_interval.lower().ceil()
while upper_ceil != lower_ceil and bits < maximum_bits:
bits += 100
x_interval = RealIntervalField(bits)(x)
upper_ceil = x_interval.upper().ceil()
lower_ceil = x_interval.lower().ceil()
if bits < maximum_bits:
return lower_ceil
else:
try:
return ceil(SR(x).full_simplify().simplify_radical())
except ValueError:
pass
raise ValueError("x (= %s) requires more than %s bits of precision to compute its ceiling"%(x, maximum_bits))
except TypeError:
# If x cannot be coerced into a RealField, then
# it should be left as a symbolic expression.
return BuiltinFunction.__call__(self, SR(x_original))
def _eval_(self, x):
"""
EXAMPLES::
sage: ceil(x).subs(x==7.5)
8
sage: ceil(x)
ceil(x)
"""
try:
return x.ceil()
except AttributeError:
if isinstance(x, (int, long)):
return Integer(x)
elif isinstance(x, (float, complex)):
return Integer(int(math.ceil(x)))
return None
ceil = Function_ceil()
class Function_floor(BuiltinFunction):
def __init__(self):
r"""
The floor function.
The floor of `x` is computed in the following manner.
#. The ``x.floor()`` method is called and returned if
it is there. If it is not, then Sage checks if `x` is one
of Python's native numeric data types. If so, then it calls and
returns ``Integer(int(math.floor(x)))``.
#. Sage tries to convert `x` into a
``RealIntervalField`` with 53 bits of precision. Next,
the floors of the endpoints are computed. If they are the same,
then that value is returned. Otherwise, the precision of the
``RealIntervalField`` is increased until they do match
up or it reaches ``maximum_bits`` of precision.
#. If none of the above work, Sage returns a
symbolic ``Expression`` object.
EXAMPLES::
sage: floor(5.4)
5
sage: type(floor(5.4))
<type 'sage.rings.integer.Integer'>
sage: var('x')
x
sage: a = floor(5.4 + x); a
floor(x + 5.40000000000000)
sage: a.simplify()
floor(x + 0.40000000000000036) + 5
sage: a(x=2)
7
::
sage: floor(cos(8)/cos(2))
0
::
sage: floor(factorial(50)/exp(1))
11188719610782480504630258070757734324011354208865721592720336800
sage: floor(SR(10^50 + 10^(-50)))
100000000000000000000000000000000000000000000000000
sage: floor(SR(10^50 - 10^(-50)))
99999999999999999999999999999999999999999999999999
sage: floor(int(10^50))
100000000000000000000000000000000000000000000000000
::
sage: import numpy
sage: a = numpy.linspace(0,2,6)
sage: floor(a)
array([ 0., 0., 0., 1., 1., 2.])
Test pickling::
sage: loads(dumps(floor))
floor
"""
BuiltinFunction.__init__(self, "floor")
def _print_latex_(self, x):
r"""
EXAMPLES::
sage: latex(floor(x))
\left \lfloor x \right \rfloor
"""
return r"\left \lfloor %s \right \rfloor"%latex(x)
#FIXME: this should be moved to _eval_
def __call__(self, x, maximum_bits=20000):
"""
Allows an object of this class to behave like a function. If
``floor`` is an instance of this class, we can do ``floor(n)`` to
obtain the floor of ``n``.
TESTS::
sage: floor(SR(10^50 + 10^(-50)))
100000000000000000000000000000000000000000000000000
sage: floor(SR(10^50 - 10^(-50)))
99999999999999999999999999999999999999999999999999
sage: floor(int(10^50))
100000000000000000000000000000000000000000000000000
"""
try:
return x.floor()
except AttributeError:
if isinstance(x, (int, long)):
return Integer(x)
elif isinstance(x, (float, complex)):
return Integer(int(math.floor(x)))
elif type(x).__module__ == 'numpy':
import numpy
return numpy.floor(x)
x_original = x
from sage.rings.all import RealIntervalField
# If x can be coerced into a real interval, then we should
# try increasing the number of bits of precision until
# we get the floor at each of the endpoints is the same.
# The precision will continue to be increased up to maximum_bits
# of precision at which point it will raise a value error.
bits = 53
try:
x_interval = RealIntervalField(bits)(x)
upper_floor = x_interval.upper().floor()
lower_floor = x_interval.lower().floor()
while upper_floor != lower_floor and bits < maximum_bits:
bits += 100
x_interval = RealIntervalField(bits)(x)
upper_floor = x_interval.upper().floor()
lower_floor = x_interval.lower().floor()
if bits < maximum_bits:
return lower_floor
else:
try:
return floor(SR(x).full_simplify().simplify_radical())
except ValueError:
pass
raise ValueError("x (= %s) requires more than %s bits of precision to compute its floor"%(x, maximum_bits))
except TypeError:
# If x cannot be coerced into a RealField, then
# it should be left as a symbolic expression.
return BuiltinFunction.__call__(self, SR(x_original))
def _eval_(self, x):
"""
EXAMPLES::
sage: floor(x).subs(x==7.5)
7
sage: floor(x)
floor(x)
"""
try:
return x.floor()
except AttributeError:
if isinstance(x, (int, long)):
return Integer(x)
elif isinstance(x, (float, complex)):
return Integer(int(math.floor(x)))
return None
floor = Function_floor()
class Function_gamma(GinacFunction):
def __init__(self):
r"""
The Gamma function. This is defined by
.. math::
\Gamma(z) = \int_0^\infty t^{z-1}e^{-t} dt
for complex input `z` with real part greater than zero, and by
analytic continuation on the rest of the complex plane (except
for negative integers, which are poles).
It is computed by various libraries within Sage, depending on
the input type.
EXAMPLES::
sage: from sage.functions.other import gamma1
sage: gamma1(CDF(0.5,14))
-4.0537030780372815e-10 - 5.773299834553605e-10*I
sage: gamma1(CDF(I))
-0.15494982830181067 - 0.49801566811835607*I
Recall that `\Gamma(n)` is `n-1` factorial::
sage: gamma1(11) == factorial(10)
True
sage: gamma1(6)
120
sage: gamma1(1/2)
sqrt(pi)
sage: gamma1(-1)
Infinity
sage: gamma1(I)
gamma(I)
sage: gamma1(x/2)(x=5)
3/4*sqrt(pi)
sage: gamma1(float(6)) # For ARM: rel tol 3e-16
120.0
sage: gamma(6.)
120.000000000000
sage: gamma1(x)
gamma(x)
::
sage: gamma1(pi)
gamma(pi)
sage: gamma1(i)
gamma(I)
sage: gamma1(i).n()
-0.154949828301811 - 0.498015668118356*I
sage: gamma1(int(5))
24
::
sage: conjugate(gamma(x))
gamma(conjugate(x))
::
sage: plot(gamma1(x),(x,1,5))
To prevent automatic evaluation use the ``hold`` argument::
sage: gamma1(1/2,hold=True)
gamma(1/2)
To then evaluate again, we currently must use Maxima via
:meth:`sage.symbolic.expression.Expression.simplify`::
sage: gamma1(1/2,hold=True).simplify()
sqrt(pi)
TESTS:
We verify that we can convert this function to Maxima and
convert back to Sage::
sage: z = var('z')
sage: maxima(gamma1(z)).sage()
gamma(z)
sage: latex(gamma1(z))
\Gamma\left(z\right)
Test that Trac ticket 5556 is fixed::
sage: gamma1(3/4)
gamma(3/4)
sage: gamma1(3/4).n(100)
1.2254167024651776451290983034
Check that negative integer input works::
sage: (-1).gamma()
Infinity
sage: (-1.).gamma()
NaN
sage: CC(-1).gamma()
Infinity
sage: RDF(-1).gamma()
NaN
sage: CDF(-1).gamma()
Infinity
Check if #8297 is fixed::
sage: latex(gamma(1/4))
\Gamma\left(\frac{1}{4}\right)
Test pickling::
sage: loads(dumps(gamma(x)))
gamma(x)
"""
GinacFunction.__init__(self, "gamma", latex_name=r'\Gamma',
ginac_name='tgamma',
conversions={'mathematica':'Gamma','maple':'GAMMA'})
gamma1 = Function_gamma()
class Function_log_gamma(GinacFunction):
def __init__(self):
r"""
The principal branch of the logarithm of Gamma function.
Gamma is defined for complex input `z` with real part greater
than zero, and by analytic continuation on the rest of the
complex plane (except for negative integers, which are poles).
It is computed by the `log_gamma` function for the number type,
or by `lgamma` in Ginac, failing that.
EXAMPLES:
Numerical evaluation happens when appropriate, to the
appropriate accuracy (see #10072)::
sage: log_gamma(6)
log(120)
sage: log_gamma(6.)
4.78749174278205
sage: log_gamma(6).n()
4.78749174278205
sage: log_gamma(RealField(100)(6))
4.7874917427820459942477009345
sage: log_gamma(2.4+i)
-0.0308566579348816 + 0.693427705955790*I
sage: log_gamma(-3.1)
0.400311696703985
Symbolic input works (see #10075)::
sage: log_gamma(3*x)
log_gamma(3*x)
sage: log_gamma(3+i)
log_gamma(I + 3)
sage: log_gamma(3+i+x)
log_gamma(x + I + 3)
To get evaluation of input for which gamma
is negative and the ceiling is even, we must
explicitly make the input complex. This is
a known issue, see #12521::
sage: log_gamma(-2.1)
NaN
sage: log_gamma(CC(-2.1))
1.53171380819509 + 3.14159265358979*I
In order to prevent evaluation, use the `hold` argument;
to evaluate a held expression, use the `n()` numerical
evaluation method::
sage: log_gamma(SR(5),hold=True)
log_gamma(5)
sage: log_gamma(SR(5),hold=True).n()
3.17805383034795
TESTS::
sage: log_gamma(-2.1+i)
-1.90373724496982 - 0.901638463592247*I
sage: log_gamma(pari(6))
4.78749174278205
sage: log_gamma(CC(6))
4.78749174278205
sage: log_gamma(CC(-2.5))
-0.0562437164976740 + 3.14159265358979*I
``conjugate(log_gamma(x))==log_gamma(conjugate(x))`` unless on the branch
cut, which runs along the negative real axis.::
sage: conjugate(log_gamma(x))
conjugate(log_gamma(x))
sage: var('y', domain='positive')
y
sage: conjugate(log_gamma(y))
log_gamma(y)
sage: conjugate(log_gamma(y+I))
conjugate(log_gamma(y + I))
sage: log_gamma(-2)
+Infinity
sage: conjugate(log_gamma(-2))
+Infinity
"""
GinacFunction.__init__(self, "log_gamma", latex_name=r'\log\Gamma',
conversions={'mathematica':'LogGamma','maxima':'log_gamma'})
log_gamma = Function_log_gamma()
class Function_gamma_inc(BuiltinFunction):
def __init__(self):
r"""
The incomplete gamma function.
EXAMPLES::
sage: gamma_inc(CDF(0,1), 3)
0.003208574993369116 + 0.012406185811871568*I
sage: gamma_inc(RDF(1), 3)
0.049787068367863944
sage: gamma_inc(3,2)
gamma(3, 2)
sage: gamma_inc(x,0)
gamma(x)
sage: latex(gamma_inc(3,2))
\Gamma\left(3, 2\right)
sage: loads(dumps((gamma_inc(3,2))))
gamma(3, 2)
sage: i = ComplexField(30).0; gamma_inc(2, 1 + i)
0.70709210 - 0.42035364*I
sage: gamma_inc(2., 5)
0.0404276819945128
"""
BuiltinFunction.__init__(self, "gamma", nargs=2, latex_name=r"\Gamma",
conversions={'maxima':'gamma_incomplete', 'mathematica':'Gamma',
'maple':'GAMMA'})
def _eval_(self, x, y):
"""
EXAMPLES::
sage: gamma_inc(2.,0)
1.00000000000000
sage: gamma_inc(2,0)
1
sage: gamma_inc(1/2,2)
-sqrt(pi)*(erf(sqrt(2)) - 1)
sage: gamma_inc(1/2,1)
-sqrt(pi)*(erf(1) - 1)
sage: gamma_inc(1/2,0)
sqrt(pi)
sage: gamma_inc(x,0)
gamma(x)
sage: gamma_inc(1,2)
e^(-2)
sage: gamma_inc(0,2)
-Ei(-2)
"""
if not isinstance(x, Expression) and not isinstance(y, Expression) and \
(is_inexact(x) or is_inexact(y)):
x, y = coercion_model.canonical_coercion(x, y)
return self._evalf_(x, y, s_parent(x))
if y == 0:
return gamma(x)
if x == 1:
return exp(-y)
if x == 0:
return -Ei(-y)
if x == Rational(1)/2: #only for x>0
return sqrt(pi)*(1-erf(sqrt(y)))
return None
def _evalf_(self, x, y, parent=None, algorithm=None):
"""
EXAMPLES::
sage: gamma_inc(0,2)
-Ei(-2)
sage: gamma_inc(0,2.)
0.0489005107080611
sage: gamma_inc(3,2).n()
1.35335283236613
TESTS:
Check that :trac:`7099` is fixed::
sage: R = RealField(1024)
sage: gamma(R(9), R(10^-3)) # rel tol 1e-308
40319.99999999999999999999999999988898884344822911869926361916294165058203634104838326009191542490601781777105678829520585311300510347676330951251563007679436243294653538925717144381702105700908686088851362675381239820118402497959018315224423868693918493033078310647199219674433536605771315869983788442389633
sage: numerical_approx(gamma(9, 10^(-3)) - gamma(9), digits=40) # abs tol 1e-36
-1.110111564516556704267183273042450876294e-28
"""
if parent is None:
parent = ComplexField()
else:
parent = ComplexField(parent.precision())
return parent(x).gamma_inc(y)
# synonym.
incomplete_gamma = gamma_inc=Function_gamma_inc()
def gamma(a, *args, **kwds):
r"""
Gamma and incomplete gamma functions.
This is defined by the integral
.. math::
\Gamma(a, z) = \int_z^\infty t^{a-1}e^{-t} dt
EXAMPLES::
Recall that `\Gamma(n)` is `n-1` factorial::
sage: gamma(11) == factorial(10)
True
sage: gamma(6)
120
sage: gamma(1/2)
sqrt(pi)
sage: gamma(-4/3)
gamma(-4/3)
sage: gamma(-1)
Infinity
sage: gamma(0)
Infinity
::
sage: gamma_inc(3,2)
gamma(3, 2)
sage: gamma_inc(x,0)
gamma(x)
::
sage: gamma(5, hold=True)
gamma(5)
sage: gamma(x, 0, hold=True)
gamma(x, 0)
::
sage: gamma(CDF(0.5,14))
-4.0537030780372815e-10 - 5.773299834553605e-10*I
sage: gamma(CDF(I))
-0.15494982830181067 - 0.49801566811835607*I
The precision for the result is deduced from the precision of the
input. Convert the input to a higher precision explicitly if a result
with higher precision is desired.::
sage: t = gamma(RealField(100)(2.5)); t
1.3293403881791370204736256125
sage: t.prec()
100
sage: gamma(6)
120
sage: gamma(pi).n(100)
2.2880377953400324179595889091
sage: gamma(3/4).n(100)
1.2254167024651776451290983034
The gamma function only works with input that can be coerced to the
Symbolic Ring::