Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/symbolic/constants.py
4072 views
1
"""
2
Mathematical constants
3
4
The following standard mathematical constants are defined in Sage,
5
along with support for coercing them into GAP, PARI/GP, KASH,
6
Maxima, Mathematica, Maple, Octave, and Singular::
7
8
sage: pi
9
pi
10
sage: e # base of the natural logarithm
11
e
12
sage: NaN # Not a number
13
NaN
14
sage: golden_ratio
15
golden_ratio
16
sage: log2 # natural logarithm of the real number 2
17
log2
18
sage: euler_gamma # Euler's gamma constant
19
euler_gamma
20
sage: catalan # the Catalan constant
21
catalan
22
sage: khinchin # Khinchin's constant
23
khinchin
24
sage: twinprime
25
twinprime
26
sage: mertens
27
mertens
28
sage: brun
29
brun
30
31
Support for coercion into the various systems means that if, e.g.,
32
you want to create `\pi` in Maxima and Singular, you don't
33
have to figure out the special notation for each system. You just
34
type the following::
35
36
sage: maxima(pi)
37
%pi
38
sage: singular(pi)
39
pi
40
sage: gap(pi)
41
pi
42
sage: gp(pi)
43
3.141592653589793238462643383 # 32-bit
44
3.1415926535897932384626433832795028842 # 64-bit
45
sage: pari(pi)
46
3.14159265358979
47
sage: kash(pi) # optional
48
3.14159265358979323846264338328
49
sage: mathematica(pi) # optional
50
Pi
51
sage: maple(pi) # optional
52
Pi
53
sage: octave(pi) # optional
54
3.14159
55
56
Arithmetic operations with constants also yield constants, which
57
can be coerced into other systems or evaluated.
58
59
::
60
61
sage: a = pi + e*4/5; a
62
pi + 4/5*e
63
sage: maxima(a)
64
%pi+4*%e/5
65
sage: RealField(15)(a) # 15 *bits* of precision
66
5.316
67
sage: gp(a)
68
5.316218116357029426750873360 # 32-bit
69
5.3162181163570294267508733603616328824 # 64-bit
70
sage: print mathematica(a) # optional
71
4 E
72
--- + Pi
73
5
74
75
EXAMPLES: Decimal expansions of constants
76
77
We can obtain floating point approximations to each of these
78
constants by coercing into the real field with given precision. For
79
example, to 200 decimal places we have the following::
80
81
sage: R = RealField(200); R
82
Real Field with 200 bits of precision
83
84
::
85
86
sage: R(pi)
87
3.1415926535897932384626433832795028841971693993751058209749
88
89
::
90
91
sage: R(e)
92
2.7182818284590452353602874713526624977572470936999595749670
93
94
::
95
96
sage: R(NaN)
97
NaN
98
99
::
100
101
sage: R(golden_ratio)
102
1.6180339887498948482045868343656381177203091798057628621354
103
104
::
105
106
sage: R(log2)
107
0.69314718055994530941723212145817656807550013436025525412068
108
109
::
110
111
sage: R(euler_gamma)
112
0.57721566490153286060651209008240243104215933593992359880577
113
114
::
115
116
sage: R(catalan)
117
0.91596559417721901505460351493238411077414937428167213426650
118
119
::
120
121
sage: R(khinchin)
122
2.6854520010653064453097148354817956938203822939944629530512
123
124
EXAMPLES: Arithmetic with constants
125
126
::
127
128
sage: f = I*(e+1); f
129
I*e + I
130
sage: f^2
131
(I*e + I)^2
132
sage: _.expand()
133
-2*e - e^2 - 1
134
135
::
136
137
sage: pp = pi+pi; pp
138
2*pi
139
sage: R(pp)
140
6.2831853071795864769252867665590057683943387987502116419499
141
142
::
143
144
sage: s = (1 + e^pi); s
145
e^pi + 1
146
sage: R(s)
147
24.140692632779269005729086367948547380266106242600211993445
148
sage: R(s-1)
149
23.140692632779269005729086367948547380266106242600211993445
150
151
::
152
153
sage: l = (1-log2)/(1+log2); l
154
-(log2 - 1)/(log2 + 1)
155
sage: R(l)
156
0.18123221829928249948761381864650311423330609774776013488056
157
158
::
159
160
sage: pim = maxima(pi)
161
sage: maxima.eval('fpprec : 100')
162
'100'
163
sage: pim.bfloat()
164
3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068b0
165
166
AUTHORS:
167
168
- Alex Clemesha (2006-01-15)
169
170
- William Stein
171
172
- Alex Clemesha, William Stein (2006-02-20): added new constants;
173
removed todos
174
175
- Didier Deshommes (2007-03-27): added constants from RQDF (deprecated)
176
177
TESTS:
178
179
Coercing the sum of a bunch of the constants to many different
180
floating point rings::
181
182
sage: a = pi + e + golden_ratio + log2 + euler_gamma + catalan + khinchin + twinprime + mertens; a
183
pi + euler_gamma + catalan + golden_ratio + log2 + khinchin + twinprime + mertens + e
184
sage: parent(a)
185
Symbolic Ring
186
sage: RR(a)
187
13.2713479401972
188
sage: RealField(212)(a)
189
13.2713479401972493100988191995758139408711068200030748178329712
190
sage: RealField(230)(a)
191
13.271347940197249310098819199575813940871106820003074817832971189555
192
sage: CC(a)
193
13.2713479401972
194
sage: CDF(a)
195
13.2713479402
196
sage: ComplexField(230)(a)
197
13.271347940197249310098819199575813940871106820003074817832971189555
198
sage: RDF(a)
199
13.2713479402
200
201
Test if #8237 is fixed::
202
203
sage: maxima('infinity').sage()
204
Infinity
205
sage: maxima('inf').sage()
206
+Infinity
207
sage: maxima('minf').sage()
208
-Infinity
209
"""
210
###############################################################################
211
# Sage: Open Source Mathematical Software
212
# Copyright (C) 2008 William Stein <[email protected]>
213
# Copyright (C) 2008-2010 Burcin Erocal <[email protected]>
214
# 2009 Mike Hansen <[email protected]>
215
# Distributed under the terms of the GNU General Public License (GPL),
216
# version 2 or any later version. The full text of the GPL is available at:
217
# http://www.gnu.org/licenses/
218
###############################################################################
219
import math
220
from functools import partial
221
from sage.rings.infinity import (infinity, minus_infinity,
222
unsigned_infinity)
223
224
constants_table = {}
225
constants_name_table = {}
226
constants_name_table[repr(infinity)] = infinity
227
constants_name_table[repr(unsigned_infinity)] = unsigned_infinity
228
constants_name_table[repr(minus_infinity)] = minus_infinity
229
230
import sage.symbolic.pynac
231
sage.symbolic.pynac.register_symbol(infinity, {'maxima':'inf'})
232
sage.symbolic.pynac.register_symbol(minus_infinity, {'maxima':'minf'})
233
sage.symbolic.pynac.register_symbol(unsigned_infinity, {'maxima':'infinity'})
234
235
from pynac import I
236
sage.symbolic.pynac.register_symbol(I, {'mathematica':'I'})
237
238
239
def unpickle_Constant(class_name, name, conversions, latex, mathml, domain):
240
"""
241
EXAMPLES::
242
243
sage: from sage.symbolic.constants import unpickle_Constant
244
sage: a = unpickle_Constant('Constant', 'a', {}, 'aa', '', 'positive')
245
sage: a.domain()
246
'positive'
247
sage: latex(a)
248
aa
249
250
Note that if the name already appears in the
251
``constants_name_table``, then that will be returned instead of
252
constructing a new object::
253
254
sage: pi = unpickle_Constant('Pi', 'pi', None, None, None, None)
255
sage: pi._maxima_init_()
256
'%pi'
257
"""
258
if name in constants_name_table:
259
return constants_name_table[name]
260
if class_name == "Constant":
261
return Constant(name, conversions=conversions, latex=latex,
262
mathml=mathml, domain=domain)
263
else:
264
cls = globals()[class_name]
265
return cls(name=name)
266
267
class Constant(object):
268
def __init__(self, name, conversions=None, latex=None, mathml="",
269
domain='complex'):
270
"""
271
EXAMPLES::
272
273
sage: from sage.symbolic.constants import Constant
274
sage: p = Constant('p')
275
sage: loads(dumps(p))
276
p
277
"""
278
self._conversions = conversions if conversions is not None else {}
279
self._latex = latex if latex is not None else name
280
self._mathml = mathml
281
self._name = name
282
self._domain = domain
283
284
for system, value in self._conversions.items():
285
setattr(self, "_%s_"%system, partial(self._generic_interface, value))
286
setattr(self, "_%s_init_"%system, partial(self._generic_interface_init, value))
287
288
from sage.symbolic.constants_c import PynacConstant
289
self._pynac = PynacConstant(self._name, self._latex, self._domain)
290
self._serial = self._pynac.serial()
291
constants_table[self._serial] = self
292
constants_name_table[self._name] = self
293
294
from sage.symbolic.pynac import register_symbol
295
register_symbol(self.expression(), self._conversions)
296
297
def __eq__(self, other):
298
"""
299
EXAMPLES::
300
301
sage: from sage.symbolic.constants import Constant
302
sage: p = Constant('p')
303
sage: s = Constant('s')
304
sage: p == p
305
True
306
sage: p == s
307
False
308
sage: p != s
309
True
310
"""
311
return (self.__class__ == other.__class__ and
312
self._name == other._name)
313
314
def __reduce__(self):
315
"""
316
Adds support for pickling constants.
317
318
EXAMPLES::
319
320
sage: from sage.symbolic.constants import Constant
321
sage: p = Constant('p')
322
sage: p.__reduce__()
323
(<function unpickle_Constant at 0x...>,
324
('Constant', 'p', {}, 'p', '', 'complex'))
325
sage: loads(dumps(p))
326
p
327
328
sage: pi.pyobject().__reduce__()
329
(<function unpickle_Constant at 0x...>,
330
('Pi',
331
'pi',
332
...,
333
'\\pi',
334
'<mi>&pi;</mi>',
335
'positive'))
336
sage: loads(dumps(pi.pyobject()))
337
pi
338
339
"""
340
return (unpickle_Constant, (self.__class__.__name__, self._name,
341
self._conversions, self._latex,
342
self._mathml, self._domain))
343
344
345
def domain(self):
346
"""
347
Returns the domain of this constant. This is either positive,
348
real, or complex, and is used by Pynac to make inferences
349
about expressions containing this constant.
350
351
EXAMPLES::
352
353
sage: p = pi.pyobject(); p
354
pi
355
sage: type(_)
356
<class 'sage.symbolic.constants.Pi'>
357
sage: p.domain()
358
'positive'
359
"""
360
return self._domain
361
362
def expression(self):
363
"""
364
Returns an expression for this constant.
365
366
EXAMPLES::
367
368
sage: a = pi.pyobject()
369
sage: pi2 = a.expression()
370
sage: pi2
371
pi
372
sage: pi2 + 2
373
pi + 2
374
sage: pi - pi2
375
0
376
"""
377
return self._pynac.expression()
378
379
def name(self):
380
"""
381
Returns the name of this constant.
382
383
EXAMPLES::
384
385
sage: from sage.symbolic.constants import Constant
386
sage: c = Constant('c')
387
sage: c.name()
388
'c'
389
"""
390
return self._name
391
392
def __repr__(self):
393
"""
394
EXAMPLES::
395
396
sage: from sage.symbolic.constants import Constant
397
sage: c = Constant('c')
398
sage: c
399
c
400
"""
401
return self._name
402
403
def _latex_(self):
404
r"""
405
EXAMPLES::
406
407
sage: from sage.symbolic.constants import Constant
408
sage: c = Constant('c', latex=r'\xi')
409
sage: latex(c)
410
\xi
411
"""
412
return self._latex
413
414
def _mathml_(self):
415
"""
416
EXAMPLES::
417
418
sage: from sage.symbolic.constants import Constant
419
sage: c = Constant('c', mathml=r'<mi>c</mi>')
420
sage: mathml(c)
421
<mi>c</mi>
422
"""
423
return self._mathml
424
425
def _generic_interface(self, value, I):
426
"""
427
This is a helper method used in defining the ``_X_`` methods
428
where ``X`` is the name of some interface.
429
430
EXAMPLES::
431
432
sage: from sage.symbolic.constants import Constant
433
sage: p = Constant('p', conversions=dict(maxima='%pi'))
434
sage: p._maxima_(maxima)
435
%pi
436
437
The above ``_maxima_`` is constructed like ``m`` below::
438
439
sage: from functools import partial
440
sage: m = partial(p._generic_interface, '%pi')
441
sage: m(maxima)
442
%pi
443
444
"""
445
return I(value)
446
447
def _generic_interface_init(self, value):
448
"""
449
This is a helper method used in defining the ``_X_init_`` methods
450
where ``X`` is the name of some interface.
451
452
EXAMPLES::
453
454
sage: from sage.symbolic.constants import Constant
455
sage: p = Constant('p', conversions=dict(maxima='%pi'))
456
sage: p._maxima_init_()
457
'%pi'
458
459
The above ``_maxima_init_`` is constructed like ``mi`` below::
460
461
sage: from functools import partial
462
sage: mi = partial(p._generic_interface_init, '%pi')
463
sage: mi()
464
'%pi'
465
466
"""
467
return value
468
469
def _interface_(self, I):
470
"""
471
EXAMPLES::
472
473
sage: from sage.symbolic.constants import Constant
474
sage: p = Constant('p', conversions=dict(maxima='%pi'))
475
sage: p._interface_(maxima)
476
%pi
477
"""
478
try:
479
s = self._conversions[I.name()]
480
return I(s)
481
except KeyError:
482
pass
483
484
try:
485
return getattr(self, "_%s_"%(I.name()))(I)
486
except AttributeError:
487
pass
488
489
raise NotImplementedError
490
491
def _gap_(self, gap):
492
"""
493
Returns the constant as a string in GAP. Since GAP does not
494
have floating point numbers, we simply return the constant as
495
a string.
496
497
EXAMPLES::
498
499
sage: from sage.symbolic.constants import Constant
500
sage: p = Constant('p')
501
sage: gap(p)
502
p
503
"""
504
return gap('"%s"'%self)
505
506
def _singular_(self, singular):
507
"""
508
Returns the constant as a string in Singular. Since Singular
509
does not always support floating point numbers, we simply
510
return the constant as a string. (Singular allows floating point
511
numbers if the current ring has floating point coefficients,
512
but not otherwise.)
513
514
EXAMPLES::
515
516
sage: from sage.symbolic.constants import Constant
517
sage: p = Constant('p')
518
sage: singular(p)
519
p
520
"""
521
return singular('"%s"'%self)
522
523
524
class Pi(Constant):
525
def __init__(self, name="pi"):
526
"""
527
TESTS::
528
529
sage: pi._latex_()
530
'\\pi'
531
sage: latex(pi)
532
\pi
533
sage: mathml(pi)
534
<mi>&pi;</mi>
535
536
"""
537
conversions = dict(axiom='%pi', maxima='%pi', giac='pi', gp='Pi', kash='PI',
538
mathematica='Pi', matlab='pi', maple='pi',
539
octave='pi', pari='Pi', pynac='Pi')
540
Constant.__init__(self, name, conversions=conversions,
541
latex=r"\pi", mathml="<mi>&pi;</mi>",
542
domain='positive')
543
544
def __float__(self):
545
"""
546
EXAMPLES::
547
548
sage: float(pi)
549
3.141592653589793
550
"""
551
return math.pi
552
553
def _mpfr_(self, R):
554
"""
555
EXAMPLES::
556
557
sage: pi._mpfr_(RealField(100))
558
3.1415926535897932384626433833
559
"""
560
return R.pi()
561
562
def _real_double_(self, R):
563
"""
564
EXAMPLES::
565
566
sage: pi._real_double_(RDF)
567
3.14159265359
568
"""
569
return R.pi()
570
571
def _sympy_(self):
572
"""
573
Converts pi to sympy pi.
574
575
EXAMPLES::
576
577
sage: import sympy
578
sage: sympy.pi == pi # indirect doctest
579
True
580
"""
581
import sympy
582
return sympy.pi
583
584
pi = Pi().expression()
585
586
"""
587
The formal square root of -1.
588
589
EXAMPLES::
590
591
sage: I
592
I
593
sage: I^2
594
-1
595
596
Note that conversions to real fields will give TypeErrors::
597
598
sage: float(I)
599
Traceback (most recent call last):
600
...
601
TypeError: unable to simplify to float approximation
602
sage: gp(I)
603
I
604
sage: RR(I)
605
Traceback (most recent call last):
606
...
607
TypeError: Unable to convert x (='1.00000000000000*I') to real number.
608
609
Expressions involving I that are real-valued can be converted to real fields::
610
611
sage: float(I*I)
612
-1.0
613
sage: RR(I*I)
614
-1.00000000000000
615
616
We can convert to complex fields::
617
618
sage: C = ComplexField(200); C
619
Complex Field with 200 bits of precision
620
sage: C(I)
621
1.0000000000000000000000000000000000000000000000000000000000*I
622
sage: I._complex_mpfr_field_(ComplexField(53))
623
1.00000000000000*I
624
625
sage: I._complex_double_(CDF)
626
1.0*I
627
sage: CDF(I)
628
1.0*I
629
630
sage: z = I + I; z
631
2*I
632
sage: C(z)
633
2.0000000000000000000000000000000000000000000000000000000000*I
634
sage: 1e8*I
635
1.00000000000000e8*I
636
637
sage: complex(I)
638
1j
639
640
sage: QQbar(I)
641
1*I
642
643
sage: abs(I)
644
1
645
646
sage: I.minpoly()
647
x^2 + 1
648
sage: maxima(2*I)
649
2*%i
650
651
TESTS::
652
653
sage: repr(I)
654
'I'
655
sage: latex(I)
656
i
657
"""
658
659
# The base of the natural logarithm, e, is not a constant in GiNaC/Sage. It is
660
# represented by exp(1). A dummy class to make this work with arithmetic and
661
# coercion is implemented in the module sage.symbolic.constants_c for speed.
662
from sage.symbolic.constants_c import E
663
e = E()
664
665
class NotANumber(Constant):
666
"""
667
Not a Number
668
"""
669
def __init__(self, name="NaN"):
670
"""
671
EXAMPLES::
672
673
sage: loads(dumps(NaN))
674
NaN
675
"""
676
conversions=dict(matlab='NaN')
677
Constant.__init__(self, name, conversions=conversions)
678
679
def __float__(self):
680
"""
681
EXAMPLES::
682
683
sage: float(NaN)
684
nan
685
"""
686
return float('nan')
687
688
def _mpfr_(self,R):
689
"""
690
EXAMPLES::
691
692
sage: NaN._mpfr_(RealField(53))
693
NaN
694
sage: type(_)
695
<type 'sage.rings.real_mpfr.RealNumber'>
696
"""
697
return R('NaN') #??? nan in mpfr: void mpfr_set_nan (mpfr_t x)
698
699
def _real_double_(self, R):
700
"""
701
EXAMPLES::
702
703
sage: RDF(NaN)
704
NaN
705
"""
706
return R.NaN()
707
708
def _sympy_(self):
709
"""
710
Converts NaN to SymPy NaN.
711
712
EXAMPLES::
713
714
sage: import sympy
715
sage: sympy.nan == NaN # indirect doctest
716
True
717
"""
718
import sympy
719
return sympy.nan
720
721
NaN = NotANumber().expression()
722
723
class GoldenRatio(Constant):
724
"""
725
The number (1+sqrt(5))/2
726
727
EXAMPLES::
728
729
sage: gr = golden_ratio
730
sage: RR(gr)
731
1.61803398874989
732
sage: R = RealField(200)
733
sage: R(gr)
734
1.6180339887498948482045868343656381177203091798057628621354
735
sage: grm = maxima(golden_ratio);grm
736
(sqrt(5)+1)/2
737
sage: grm + grm
738
sqrt(5)+1
739
sage: float(grm + grm)
740
3.23606797749979
741
"""
742
def __init__(self, name='golden_ratio'):
743
"""
744
EXAMPLES::
745
746
sage: loads(dumps(golden_ratio))
747
golden_ratio
748
"""
749
conversions = dict(mathematica='(1+Sqrt[5])/2', gp='(1+sqrt(5))/2',
750
maple='(1+sqrt(5))/2', maxima='(1+sqrt(5))/2',
751
pari='(1+sqrt(5))/2', octave='(1+sqrt(5))/2',
752
kash='(1+Sqrt(5))/2', giac='(1+sqrt(5))/2')
753
Constant.__init__(self, name, conversions=conversions,
754
latex=r'\phi', domain='positive')
755
756
def minpoly(self, bits=None, degree=None, epsilon=0):
757
"""
758
EXAMPLES::
759
760
sage: golden_ratio.minpoly()
761
x^2 - x - 1
762
"""
763
from sage.rings.all import QQ
764
x = QQ['x'].gen(0)
765
return x**2 - x - 1
766
767
def __float__(self):
768
"""
769
EXAMPLES::
770
771
sage: float(golden_ratio)
772
1.618033988749895
773
sage: golden_ratio.__float__()
774
1.618033988749895
775
"""
776
return float(0.5)*(float(1.0)+math.sqrt(float(5.0)))
777
778
def _real_double_(self, R):
779
"""
780
EXAMPLES::
781
782
sage: RDF(golden_ratio)
783
1.61803398875
784
"""
785
return R('1.61803398874989484820458')
786
787
788
def _mpfr_(self,R):
789
"""
790
EXAMPLES::
791
792
sage: golden_ratio._mpfr_(RealField(100))
793
1.6180339887498948482045868344
794
sage: RealField(100)(golden_ratio)
795
1.6180339887498948482045868344
796
"""
797
return (R(1)+R(5).sqrt())/R(2)
798
799
def _algebraic_(self, field):
800
"""
801
EXAMPLES::
802
803
sage: golden_ratio._algebraic_(QQbar)
804
1.618033988749895?
805
sage: QQbar(golden_ratio)
806
1.618033988749895?
807
"""
808
import sage.rings.qqbar
809
return field(sage.rings.qqbar.get_AA_golden_ratio())
810
811
def _sympy_(self):
812
"""
813
Converts golden_ratio to SymPy GoldenRation.
814
815
EXAMPLES::
816
817
sage: import sympy
818
sage: sympy.GoldenRatio == golden_ratio # indirect doctest
819
True
820
"""
821
import sympy
822
return sympy.GoldenRatio
823
824
golden_ratio = GoldenRatio().expression()
825
826
class Log2(Constant):
827
"""
828
The natural logarithm of the real number 2.
829
830
EXAMPLES::
831
832
sage: log2
833
log2
834
sage: float(log2)
835
0.6931471805599453
836
sage: RR(log2)
837
0.693147180559945
838
sage: R = RealField(200); R
839
Real Field with 200 bits of precision
840
sage: R(log2)
841
0.69314718055994530941723212145817656807550013436025525412068
842
sage: l = (1-log2)/(1+log2); l
843
-(log2 - 1)/(log2 + 1)
844
sage: R(l)
845
0.18123221829928249948761381864650311423330609774776013488056
846
sage: maxima(log2)
847
log(2)
848
sage: maxima(log2).float()
849
.6931471805599453
850
sage: gp(log2)
851
0.6931471805599453094172321215 # 32-bit
852
0.69314718055994530941723212145817656808 # 64-bit
853
sage: RealField(150)(2).log()
854
0.69314718055994530941723212145817656807550013
855
"""
856
def __init__(self, name='log2'):
857
"""
858
EXAMPLES::
859
860
sage: loads(dumps(log2))
861
log2
862
"""
863
conversions = dict(mathematica='Log[2]', kash='Log(2)',
864
maple='log(2)', maxima='log(2)', gp='log(2)',
865
pari='log(2)', octave='log(2)')
866
Constant.__init__(self, name, conversions=conversions,
867
latex=r'\log(2)', domain='positive')
868
869
def __float__(self):
870
"""
871
EXAMPLES::
872
873
sage: float(log2)
874
0.6931471805599453
875
sage: log2.__float__()
876
0.6931471805599453
877
"""
878
return math.log(2)
879
880
def _real_double_(self, R):
881
"""
882
EXAMPLES::
883
884
sage: RDF(log2)
885
0.69314718056
886
"""
887
return R.log2()
888
889
890
def _mpfr_(self,R):
891
"""
892
EXAMPLES::
893
894
sage: RealField(100)(log2)
895
0.69314718055994530941723212146
896
sage: log2._mpfr_(RealField(100))
897
0.69314718055994530941723212146
898
"""
899
return R.log2()
900
901
log2 = Log2().expression()
902
903
class EulerGamma(Constant):
904
"""
905
The limiting difference between the harmonic series and the natural
906
logarithm.
907
908
EXAMPLES::
909
910
sage: R = RealField()
911
sage: R(euler_gamma)
912
0.577215664901533
913
sage: R = RealField(200); R
914
Real Field with 200 bits of precision
915
sage: R(euler_gamma)
916
0.57721566490153286060651209008240243104215933593992359880577
917
sage: eg = euler_gamma + euler_gamma; eg
918
2*euler_gamma
919
sage: R(eg)
920
1.1544313298030657212130241801648048620843186718798471976115
921
"""
922
def __init__(self, name='euler_gamma'):
923
"""
924
EXAMPLES::
925
926
sage: loads(dumps(euler_gamma))
927
euler_gamma
928
"""
929
conversions = dict(kash='EulerGamma(R)', maple='gamma',
930
mathematica='EulerGamma', pari='Euler',
931
maxima='%gamma', pynac='Euler')
932
Constant.__init__(self, name, conversions=conversions,
933
latex=r'\gamma', domain='positive')
934
935
def _mpfr_(self,R):
936
"""
937
EXAMPLES::
938
939
sage: RealField(100)(euler_gamma)
940
0.57721566490153286060651209008
941
sage: euler_gamma._mpfr_(RealField(100))
942
0.57721566490153286060651209008
943
"""
944
return R.euler_constant()
945
946
def __float__(self):
947
"""
948
EXAMPLES::
949
950
sage: float(euler_gamma)
951
0.5772156649015329
952
"""
953
return 0.57721566490153286060651209008
954
955
def _real_double_(self, R):
956
"""
957
EXAMPLES::
958
959
sage: RDF(euler_gamma)
960
0.577215664902
961
"""
962
return R.euler_constant()
963
964
def _sympy_(self):
965
"""
966
Converts euler_gamma to SymPy EulerGamma.
967
968
EXAMPLES::
969
970
sage: import sympy
971
sage: sympy.EulerGamma == euler_gamma # indirect doctest
972
True
973
"""
974
import sympy
975
return sympy.EulerGamma
976
977
euler_gamma = EulerGamma().expression()
978
979
class Catalan(Constant):
980
"""
981
A number appearing in combinatorics defined as the Dirichlet beta
982
function evaluated at the number 2.
983
984
EXAMPLES::
985
986
sage: catalan^2 + mertens
987
mertens + catalan^2
988
"""
989
def __init__(self, name='catalan'):
990
"""
991
EXAMPLES::
992
993
sage: loads(dumps(catalan))
994
catalan
995
"""
996
#kash: R is default prec
997
conversions = dict(mathematica='Catalan', kash='Catalan(R)',
998
maple='Catalan', maxima='catalan',
999
pynac='Catalan')
1000
Constant.__init__(self, name, conversions=conversions,
1001
domain='positive')
1002
1003
1004
def _mpfr_(self, R):
1005
"""
1006
EXAMPLES::
1007
1008
sage: RealField(100)(catalan)
1009
0.91596559417721901505460351493
1010
sage: catalan._mpfr_(RealField(100))
1011
0.91596559417721901505460351493
1012
"""
1013
return R.catalan_constant()
1014
1015
def _real_double_(self, R):
1016
"""
1017
EXAMPLES: We coerce to the real double field::
1018
1019
sage: RDF(catalan)
1020
0.915965594177
1021
"""
1022
return R('0.91596559417721901505460351493252')
1023
1024
1025
def __float__(self):
1026
"""
1027
EXAMPLES::
1028
1029
sage: float(catalan)
1030
0.915965594177219
1031
"""
1032
return 0.91596559417721901505460351493252
1033
1034
def _sympy_(self):
1035
"""
1036
Converts catalan to SymPy Catalan.
1037
1038
EXAMPLES::
1039
1040
sage: import sympy
1041
sage: sympy.Catalan == catalan # indirect doctest
1042
True
1043
"""
1044
import sympy
1045
return sympy.Catalan
1046
1047
catalan = Catalan().expression()
1048
1049
class Khinchin(Constant):
1050
"""
1051
The geometric mean of the continued fraction expansion of any
1052
(almost any) real number.
1053
1054
EXAMPLES::
1055
1056
sage: float(khinchin)
1057
2.6854520010653062
1058
sage: khinchin.n(digits=60)
1059
2.68545200106530644530971483548179569382038229399446295305115
1060
sage: m = mathematica(khinchin); m # optional
1061
Khinchin
1062
sage: m.N(200) # optional
1063
2.68545200106530644530971483548179569382038229399446295305115234555721885953715200280114117493184769799515346590528809008289767771641096305179253348325966838185231542133211949962603932852204481940961807 # 32-bit
1064
2.6854520010653064453097148354817956938203822939944629530511523455572188595371520028011411749318476979951534659052880900828976777164109630517925334832596683818523154213321194996260393285220448194096181 # 64-bit
1065
"""
1066
def __init__(self, name='khinchin'):
1067
"""
1068
EXAMPLES::
1069
1070
sage: loads(dumps(khinchin))
1071
khinchin
1072
"""
1073
conversions = dict(maxima='khinchin', mathematica='Khinchin',
1074
pynac='Khinchin')
1075
Constant.__init__(self, name, conversions=conversions,
1076
domain='positive')
1077
1078
def _mpfr_(self, R):
1079
"""
1080
EXAMPLES::
1081
1082
sage: khinchin._mpfr_(RealField(100))
1083
2.6854520010653064453097148355
1084
sage: RealField(100)(khinchin)
1085
2.6854520010653064453097148355
1086
1087
"""
1088
import sage.libs.mpmath.all as a
1089
return a.eval_constant('khinchin', R)
1090
1091
def __float__(self):
1092
"""
1093
EXAMPLES::
1094
1095
sage: float(khinchin)
1096
2.6854520010653062
1097
"""
1098
return 2.6854520010653064453097148355
1099
1100
khinchin = Khinchin().expression()
1101
1102
class TwinPrime(Constant):
1103
r"""
1104
The Twin Primes constant is defined as
1105
`\prod 1 - 1/(p-1)^2` for primes `p > 2`.
1106
1107
EXAMPLES::
1108
1109
sage: float(twinprime)
1110
0.6601618158468696
1111
sage: twinprime.n(digits=60)
1112
0.660161815846869573927812110014555778432623360284733413319448
1113
1114
"""
1115
def __init__(self, name='twinprime'):
1116
"""
1117
EXAMPLES::
1118
1119
sage: loads(dumps(twinprime))
1120
twinprime
1121
"""
1122
conversions = dict(maxima='twinprime', pynac='TwinPrime')
1123
Constant.__init__(self, name, conversions=conversions,
1124
domain='positive')
1125
1126
def _mpfr_(self, R):
1127
"""
1128
EXAMPLES::
1129
1130
sage: twinprime._mpfr_(RealField(100))
1131
0.66016181584686957392781211001
1132
sage: RealField(100)(twinprime)
1133
0.66016181584686957392781211001
1134
"""
1135
import sage.libs.mpmath.all as a
1136
return a.eval_constant('twinprime', R)
1137
1138
def __float__(self):
1139
"""
1140
EXAMPLES::
1141
1142
sage: float(twinprime)
1143
0.6601618158468696
1144
"""
1145
return 0.66016181584686957392781211001
1146
1147
twinprime = TwinPrime().expression()
1148
1149
class Mertens(Constant):
1150
"""
1151
The Mertens constant is related to the Twin Primes constant and
1152
appears in Mertens' second theorem.
1153
1154
EXAMPLES::
1155
1156
sage: float(mertens)
1157
0.26149721284764277
1158
sage: mertens.n(digits=60)
1159
0.261497212847642783755426838608695859051566648261199206192064
1160
1161
"""
1162
def __init__(self, name='mertens'):
1163
"""
1164
EXAMPLES::
1165
1166
sage: loads(dumps(mertens))
1167
mertens
1168
"""
1169
conversions = dict(maxima='mertens', pynac='Mertens')
1170
Constant.__init__(self, name, conversions=conversions,
1171
domain='positive')
1172
1173
def _mpfr_(self, R):
1174
"""
1175
EXAMPLES::
1176
1177
sage: mertens._mpfr_(RealField(100))
1178
0.26149721284764278375542683861
1179
sage: RealField(100)(mertens)
1180
0.26149721284764278375542683861
1181
1182
"""
1183
import sage.libs.mpmath.all as a
1184
return a.eval_constant('mertens', R)
1185
1186
def __float__(self):
1187
"""
1188
EXAMPLES::
1189
1190
sage: float(mertens)
1191
0.26149721284764277
1192
"""
1193
return 0.26149721284764278375542683861
1194
1195
merten = mertens = Mertens().expression()
1196
1197
class Glaisher(Constant):
1198
r"""
1199
The Glaisher-Kinkelin constant `A = \exp(\frac{1}{12}-\zeta'(-1))`.
1200
1201
EXAMPLES::
1202
1203
sage: float(glaisher)
1204
1.2824271291006226
1205
sage: glaisher.n(digits=60)
1206
1.28242712910062263687534256886979172776768892732500119206374
1207
sage: a = glaisher + 2
1208
sage: a
1209
glaisher + 2
1210
sage: parent(a)
1211
Symbolic Ring
1212
1213
"""
1214
def __init__(self, name='glaisher'):
1215
"""
1216
EXAMPLES::
1217
1218
sage: loads(dumps(glaisher))
1219
glaisher
1220
"""
1221
conversions = dict(maxima='glaisher', pynac='Glaisher',
1222
mathematica='Glaisher')
1223
Constant.__init__(self, name, conversions=conversions,
1224
domain='positive')
1225
1226
def _mpfr_(self, R):
1227
"""
1228
EXAMPLES::
1229
1230
sage: glaisher._mpfr_(RealField(100))
1231
1.2824271291006226368753425689
1232
sage: RealField(100)(glaisher)
1233
1.2824271291006226368753425689
1234
1235
"""
1236
import sage.libs.mpmath.all as a
1237
return a.eval_constant('glaisher', R)
1238
1239
def __float__(self):
1240
"""
1241
EXAMPLES::
1242
1243
sage: float(glaisher)
1244
1.2824271291006226
1245
"""
1246
return 1.2824271291006226368753425689
1247
1248
1249
glaisher = Glaisher().expression()
1250
1251
1252
###############################
1253
# Limited precision constants #
1254
###############################
1255
1256
# NOTE: LimitedPrecisionConstant is an *abstract base class*. It is
1257
# not instantiated. It doesn't make sense to pickle and unpickle
1258
# this, so there is no loads(dumps(...)) doctest below.
1259
1260
class LimitedPrecisionConstant(Constant):
1261
def __init__(self, name, value, **kwds):
1262
"""
1263
A class for constants that are only known to a limited
1264
precision.
1265
1266
EXAMPLES::
1267
1268
sage: from sage.symbolic.constants import LimitedPrecisionConstant
1269
sage: a = LimitedPrecisionConstant('a', '1.234567891011121314').expression(); a
1270
a
1271
sage: RDF(a)
1272
1.23456789101
1273
sage: RealField(200)(a)
1274
Traceback (most recent call last):
1275
...
1276
NotImplementedError: a is only available up to 59 bits
1277
"""
1278
self._value = value
1279
self._bits = len(self._value)*3-1 #FIXME
1280
Constant.__init__(self, name, **kwds)
1281
1282
def _mpfr_(self, R):
1283
"""
1284
EXAMPLES::
1285
1286
sage: RealField(41)(brun)
1287
1.90216058310
1288
sage: RealField(20000)(brun)
1289
Traceback (most recent call last):
1290
...
1291
NotImplementedError: brun is only available up to 41 bits
1292
"""
1293
if R.precision() <= self._bits:
1294
return R(self._value)
1295
raise NotImplementedError, "%s is only available up to %s bits"%(self.name(), self._bits)
1296
1297
def _real_double_(self, R):
1298
"""
1299
EXAMPLES::
1300
1301
sage: from sage.symbolic.constants import LimitedPrecisionConstant
1302
sage: a = LimitedPrecisionConstant('a', '1.234567891011121314').expression()
1303
sage: RDF(a)
1304
1.23456789101
1305
"""
1306
if R.precision() <= self._bits:
1307
return R(self._value)
1308
raise NotImplementedError, "%s is only available up to %s bits"%(self.name(), self._bits)
1309
1310
def __float__(self):
1311
"""
1312
EXAMPLES::
1313
1314
sage: from sage.symbolic.constants import LimitedPrecisionConstant
1315
sage: a = LimitedPrecisionConstant('a', '1.234567891011121314').expression()
1316
sage: float(a)
1317
1.2345678910111213
1318
1319
"""
1320
if self._bits < 53:
1321
raise NotImplementedError, "%s is only available up to %s bits"%(self.name(), self._bits)
1322
return float(self._value)
1323
1324
class Brun(LimitedPrecisionConstant):
1325
"""
1326
Brun's constant is the sum of reciprocals of odd twin primes.
1327
1328
It is not known to very high precision; calculating the number
1329
using twin primes up to `10^{16}` (Sebah 2002) gives the
1330
number `1.9021605831040`.
1331
1332
EXAMPLES::
1333
1334
sage: float(brun)
1335
Traceback (most recent call last):
1336
...
1337
NotImplementedError: brun is only available up to 41 bits
1338
sage: R = RealField(41); R
1339
Real Field with 41 bits of precision
1340
sage: R(brun)
1341
1.90216058310
1342
"""
1343
def __init__(self, name='brun'):
1344
"""
1345
EXAMPLES::
1346
1347
sage: loads(dumps(brun))
1348
brun
1349
"""
1350
conversions = dict(maxima='brun')
1351
1352
# digits come from Sloane's tables at http://oeis.org/classic/table?a=65421&fmt=0
1353
value = "1.902160583104"
1354
1355
LimitedPrecisionConstant.__init__(self, name, value,
1356
conversions=conversions,
1357
domain='positive')
1358
1359
brun = Brun().expression()
1360
1361