Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagesmc
Path: blob/master/src/sage/symbolic/constants.py
8817 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
-e^2 - 2*e - 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
mertens + twinprime + khinchin + log2 + golden_ratio + catalan + euler_gamma + pi + e
184
sage: parent(a)
185
Symbolic Ring
186
sage: RR(a) #abstol 1e11
187
13.2713479401972
188
sage: RealField(212)(a)
189
13.2713479401972493100988191995758139408711068200030748178329712
190
sage: RealField(230)(a)
191
13.271347940197249310098819199575813940871106820003074817832971189555
192
sage: CC(a) #abstol 1e11
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: bool(NaN._sympy_()._sage_() == NaN)
715
True
716
sage: import sympy
717
sage: sympy.nan == NaN # this should be fixed
718
False
719
"""
720
import sympy
721
return sympy.nan
722
723
NaN = NotANumber().expression()
724
725
class GoldenRatio(Constant):
726
"""
727
The number (1+sqrt(5))/2
728
729
EXAMPLES::
730
731
sage: gr = golden_ratio
732
sage: RR(gr)
733
1.61803398874989
734
sage: R = RealField(200)
735
sage: R(gr)
736
1.6180339887498948482045868343656381177203091798057628621354
737
sage: grm = maxima(golden_ratio);grm
738
(sqrt(5)+1)/2
739
sage: grm + grm
740
sqrt(5)+1
741
sage: float(grm + grm)
742
3.23606797749979
743
"""
744
def __init__(self, name='golden_ratio'):
745
"""
746
EXAMPLES::
747
748
sage: loads(dumps(golden_ratio))
749
golden_ratio
750
"""
751
conversions = dict(mathematica='(1+Sqrt[5])/2', gp='(1+sqrt(5))/2',
752
maple='(1+sqrt(5))/2', maxima='(1+sqrt(5))/2',
753
pari='(1+sqrt(5))/2', octave='(1+sqrt(5))/2',
754
kash='(1+Sqrt(5))/2', giac='(1+sqrt(5))/2')
755
Constant.__init__(self, name, conversions=conversions,
756
latex=r'\phi', domain='positive')
757
758
def minpoly(self, bits=None, degree=None, epsilon=0):
759
"""
760
EXAMPLES::
761
762
sage: golden_ratio.minpoly()
763
x^2 - x - 1
764
"""
765
from sage.rings.all import QQ
766
x = QQ['x'].gen(0)
767
return x**2 - x - 1
768
769
def __float__(self):
770
"""
771
EXAMPLES::
772
773
sage: float(golden_ratio)
774
1.618033988749895
775
sage: golden_ratio.__float__()
776
1.618033988749895
777
"""
778
return float(0.5)*(float(1.0)+math.sqrt(float(5.0)))
779
780
def _real_double_(self, R):
781
"""
782
EXAMPLES::
783
784
sage: RDF(golden_ratio)
785
1.61803398875
786
"""
787
return R('1.61803398874989484820458')
788
789
790
def _mpfr_(self,R):
791
"""
792
EXAMPLES::
793
794
sage: golden_ratio._mpfr_(RealField(100))
795
1.6180339887498948482045868344
796
sage: RealField(100)(golden_ratio)
797
1.6180339887498948482045868344
798
"""
799
return (R(1)+R(5).sqrt())/R(2)
800
801
def _algebraic_(self, field):
802
"""
803
EXAMPLES::
804
805
sage: golden_ratio._algebraic_(QQbar)
806
1.618033988749895?
807
sage: QQbar(golden_ratio)
808
1.618033988749895?
809
"""
810
import sage.rings.qqbar
811
return field(sage.rings.qqbar.get_AA_golden_ratio())
812
813
def _sympy_(self):
814
"""
815
Converts golden_ratio to SymPy GoldenRation.
816
817
EXAMPLES::
818
819
sage: import sympy
820
sage: sympy.GoldenRatio == golden_ratio # indirect doctest
821
True
822
"""
823
import sympy
824
return sympy.GoldenRatio
825
826
golden_ratio = GoldenRatio().expression()
827
828
class Log2(Constant):
829
"""
830
The natural logarithm of the real number 2.
831
832
EXAMPLES::
833
834
sage: log2
835
log2
836
sage: float(log2)
837
0.6931471805599453
838
sage: RR(log2)
839
0.693147180559945
840
sage: R = RealField(200); R
841
Real Field with 200 bits of precision
842
sage: R(log2)
843
0.69314718055994530941723212145817656807550013436025525412068
844
sage: l = (1-log2)/(1+log2); l
845
-(log2 - 1)/(log2 + 1)
846
sage: R(l)
847
0.18123221829928249948761381864650311423330609774776013488056
848
sage: maxima(log2)
849
log(2)
850
sage: maxima(log2).float()
851
.6931471805599453
852
sage: gp(log2)
853
0.6931471805599453094172321215 # 32-bit
854
0.69314718055994530941723212145817656808 # 64-bit
855
sage: RealField(150)(2).log()
856
0.69314718055994530941723212145817656807550013
857
"""
858
def __init__(self, name='log2'):
859
"""
860
EXAMPLES::
861
862
sage: loads(dumps(log2))
863
log2
864
"""
865
conversions = dict(mathematica='Log[2]', kash='Log(2)',
866
maple='log(2)', maxima='log(2)', gp='log(2)',
867
pari='log(2)', octave='log(2)')
868
Constant.__init__(self, name, conversions=conversions,
869
latex=r'\log(2)', domain='positive')
870
871
def __float__(self):
872
"""
873
EXAMPLES::
874
875
sage: float(log2)
876
0.6931471805599453
877
sage: log2.__float__()
878
0.6931471805599453
879
"""
880
return math.log(2)
881
882
def _real_double_(self, R):
883
"""
884
EXAMPLES::
885
886
sage: RDF(log2)
887
0.69314718056
888
"""
889
return R.log2()
890
891
892
def _mpfr_(self,R):
893
"""
894
EXAMPLES::
895
896
sage: RealField(100)(log2)
897
0.69314718055994530941723212146
898
sage: log2._mpfr_(RealField(100))
899
0.69314718055994530941723212146
900
"""
901
return R.log2()
902
903
log2 = Log2().expression()
904
905
class EulerGamma(Constant):
906
"""
907
The limiting difference between the harmonic series and the natural
908
logarithm.
909
910
EXAMPLES::
911
912
sage: R = RealField()
913
sage: R(euler_gamma)
914
0.577215664901533
915
sage: R = RealField(200); R
916
Real Field with 200 bits of precision
917
sage: R(euler_gamma)
918
0.57721566490153286060651209008240243104215933593992359880577
919
sage: eg = euler_gamma + euler_gamma; eg
920
2*euler_gamma
921
sage: R(eg)
922
1.1544313298030657212130241801648048620843186718798471976115
923
"""
924
def __init__(self, name='euler_gamma'):
925
"""
926
EXAMPLES::
927
928
sage: loads(dumps(euler_gamma))
929
euler_gamma
930
"""
931
conversions = dict(kash='EulerGamma(R)', maple='gamma',
932
mathematica='EulerGamma', pari='Euler',
933
maxima='%gamma', pynac='Euler')
934
Constant.__init__(self, name, conversions=conversions,
935
latex=r'\gamma', domain='positive')
936
937
def _mpfr_(self,R):
938
"""
939
EXAMPLES::
940
941
sage: RealField(100)(euler_gamma)
942
0.57721566490153286060651209008
943
sage: euler_gamma._mpfr_(RealField(100))
944
0.57721566490153286060651209008
945
"""
946
return R.euler_constant()
947
948
def __float__(self):
949
"""
950
EXAMPLES::
951
952
sage: float(euler_gamma)
953
0.5772156649015329
954
"""
955
return 0.57721566490153286060651209008
956
957
def _real_double_(self, R):
958
"""
959
EXAMPLES::
960
961
sage: RDF(euler_gamma)
962
0.577215664902
963
"""
964
return R.euler_constant()
965
966
def _sympy_(self):
967
"""
968
Converts euler_gamma to SymPy EulerGamma.
969
970
EXAMPLES::
971
972
sage: import sympy
973
sage: sympy.EulerGamma == euler_gamma # indirect doctest
974
True
975
"""
976
import sympy
977
return sympy.EulerGamma
978
979
euler_gamma = EulerGamma().expression()
980
981
class Catalan(Constant):
982
"""
983
A number appearing in combinatorics defined as the Dirichlet beta
984
function evaluated at the number 2.
985
986
EXAMPLES::
987
988
sage: catalan^2 + mertens
989
mertens + catalan^2
990
"""
991
def __init__(self, name='catalan'):
992
"""
993
EXAMPLES::
994
995
sage: loads(dumps(catalan))
996
catalan
997
"""
998
#kash: R is default prec
999
conversions = dict(mathematica='Catalan', kash='Catalan(R)',
1000
maple='Catalan', maxima='catalan',
1001
pynac='Catalan')
1002
Constant.__init__(self, name, conversions=conversions,
1003
domain='positive')
1004
1005
1006
def _mpfr_(self, R):
1007
"""
1008
EXAMPLES::
1009
1010
sage: RealField(100)(catalan)
1011
0.91596559417721901505460351493
1012
sage: catalan._mpfr_(RealField(100))
1013
0.91596559417721901505460351493
1014
"""
1015
return R.catalan_constant()
1016
1017
def _real_double_(self, R):
1018
"""
1019
EXAMPLES: We coerce to the real double field::
1020
1021
sage: RDF(catalan)
1022
0.915965594177
1023
"""
1024
return R('0.91596559417721901505460351493252')
1025
1026
1027
def __float__(self):
1028
"""
1029
EXAMPLES::
1030
1031
sage: float(catalan)
1032
0.915965594177219
1033
"""
1034
return 0.91596559417721901505460351493252
1035
1036
def _sympy_(self):
1037
"""
1038
Converts catalan to SymPy Catalan.
1039
1040
EXAMPLES::
1041
1042
sage: import sympy
1043
sage: sympy.Catalan == catalan # indirect doctest
1044
True
1045
"""
1046
import sympy
1047
return sympy.Catalan
1048
1049
catalan = Catalan().expression()
1050
1051
class Khinchin(Constant):
1052
"""
1053
The geometric mean of the continued fraction expansion of any
1054
(almost any) real number.
1055
1056
EXAMPLES::
1057
1058
sage: float(khinchin)
1059
2.6854520010653062
1060
sage: khinchin.n(digits=60)
1061
2.68545200106530644530971483548179569382038229399446295305115
1062
sage: m = mathematica(khinchin); m # optional
1063
Khinchin
1064
sage: m.N(200) # optional
1065
2.68545200106530644530971483548179569382038229399446295305115234555721885953715200280114117493184769799515346590528809008289767771641096305179253348325966838185231542133211949962603932852204481940961807 # 32-bit
1066
2.6854520010653064453097148354817956938203822939944629530511523455572188595371520028011411749318476979951534659052880900828976777164109630517925334832596683818523154213321194996260393285220448194096181 # 64-bit
1067
"""
1068
def __init__(self, name='khinchin'):
1069
"""
1070
EXAMPLES::
1071
1072
sage: loads(dumps(khinchin))
1073
khinchin
1074
"""
1075
conversions = dict(maxima='khinchin', mathematica='Khinchin',
1076
pynac='Khinchin')
1077
Constant.__init__(self, name, conversions=conversions,
1078
domain='positive')
1079
1080
def _mpfr_(self, R):
1081
"""
1082
EXAMPLES::
1083
1084
sage: khinchin._mpfr_(RealField(100))
1085
2.6854520010653064453097148355
1086
sage: RealField(100)(khinchin)
1087
2.6854520010653064453097148355
1088
1089
"""
1090
import sage.libs.mpmath.all as a
1091
return a.eval_constant('khinchin', R)
1092
1093
def __float__(self):
1094
"""
1095
EXAMPLES::
1096
1097
sage: float(khinchin)
1098
2.6854520010653062
1099
"""
1100
return 2.6854520010653064453097148355
1101
1102
khinchin = Khinchin().expression()
1103
1104
class TwinPrime(Constant):
1105
r"""
1106
The Twin Primes constant is defined as
1107
`\prod 1 - 1/(p-1)^2` for primes `p > 2`.
1108
1109
EXAMPLES::
1110
1111
sage: float(twinprime)
1112
0.6601618158468696
1113
sage: twinprime.n(digits=60)
1114
0.660161815846869573927812110014555778432623360284733413319448
1115
1116
"""
1117
def __init__(self, name='twinprime'):
1118
"""
1119
EXAMPLES::
1120
1121
sage: loads(dumps(twinprime))
1122
twinprime
1123
"""
1124
conversions = dict(maxima='twinprime', pynac='TwinPrime')
1125
Constant.__init__(self, name, conversions=conversions,
1126
domain='positive')
1127
1128
def _mpfr_(self, R):
1129
"""
1130
EXAMPLES::
1131
1132
sage: twinprime._mpfr_(RealField(100))
1133
0.66016181584686957392781211001
1134
sage: RealField(100)(twinprime)
1135
0.66016181584686957392781211001
1136
"""
1137
import sage.libs.mpmath.all as a
1138
return a.eval_constant('twinprime', R)
1139
1140
def __float__(self):
1141
"""
1142
EXAMPLES::
1143
1144
sage: float(twinprime)
1145
0.6601618158468696
1146
"""
1147
return 0.66016181584686957392781211001
1148
1149
twinprime = TwinPrime().expression()
1150
1151
1152
class Mertens(Constant):
1153
"""
1154
The Mertens constant is related to the Twin Primes constant and
1155
appears in Mertens' second theorem.
1156
1157
EXAMPLES::
1158
1159
sage: float(mertens)
1160
0.26149721284764277
1161
sage: mertens.n(digits=60)
1162
0.261497212847642783755426838608695859051566648261199206192064
1163
1164
"""
1165
def __init__(self, name='mertens'):
1166
"""
1167
EXAMPLES::
1168
1169
sage: loads(dumps(mertens))
1170
mertens
1171
"""
1172
conversions = dict(maxima='mertens', pynac='Mertens')
1173
Constant.__init__(self, name, conversions=conversions,
1174
domain='positive')
1175
1176
def _mpfr_(self, R):
1177
"""
1178
EXAMPLES::
1179
1180
sage: mertens._mpfr_(RealField(100))
1181
0.26149721284764278375542683861
1182
sage: RealField(100)(mertens)
1183
0.26149721284764278375542683861
1184
1185
"""
1186
import sage.libs.mpmath.all as a
1187
return a.eval_constant('mertens', R)
1188
1189
def __float__(self):
1190
"""
1191
EXAMPLES::
1192
1193
sage: float(mertens)
1194
0.26149721284764277
1195
"""
1196
return 0.26149721284764278375542683861
1197
1198
mertens = Mertens().expression()
1199
1200
1201
class Glaisher(Constant):
1202
r"""
1203
The Glaisher-Kinkelin constant `A = \exp(\frac{1}{12}-\zeta'(-1))`.
1204
1205
EXAMPLES::
1206
1207
sage: float(glaisher)
1208
1.2824271291006226
1209
sage: glaisher.n(digits=60)
1210
1.28242712910062263687534256886979172776768892732500119206374
1211
sage: a = glaisher + 2
1212
sage: a
1213
glaisher + 2
1214
sage: parent(a)
1215
Symbolic Ring
1216
1217
"""
1218
def __init__(self, name='glaisher'):
1219
"""
1220
EXAMPLES::
1221
1222
sage: loads(dumps(glaisher))
1223
glaisher
1224
"""
1225
conversions = dict(maxima='glaisher', pynac='Glaisher',
1226
mathematica='Glaisher')
1227
Constant.__init__(self, name, conversions=conversions,
1228
domain='positive')
1229
1230
def _mpfr_(self, R):
1231
"""
1232
EXAMPLES::
1233
1234
sage: glaisher._mpfr_(RealField(100))
1235
1.2824271291006226368753425689
1236
sage: RealField(100)(glaisher)
1237
1.2824271291006226368753425689
1238
1239
"""
1240
import sage.libs.mpmath.all as a
1241
return a.eval_constant('glaisher', R)
1242
1243
def __float__(self):
1244
"""
1245
EXAMPLES::
1246
1247
sage: float(glaisher)
1248
1.2824271291006226
1249
"""
1250
return 1.2824271291006226368753425689
1251
1252
1253
glaisher = Glaisher().expression()
1254
1255
1256
###############################
1257
# Limited precision constants #
1258
###############################
1259
1260
# NOTE: LimitedPrecisionConstant is an *abstract base class*. It is
1261
# not instantiated. It doesn't make sense to pickle and unpickle
1262
# this, so there is no loads(dumps(...)) doctest below.
1263
1264
class LimitedPrecisionConstant(Constant):
1265
def __init__(self, name, value, **kwds):
1266
"""
1267
A class for constants that are only known to a limited
1268
precision.
1269
1270
EXAMPLES::
1271
1272
sage: from sage.symbolic.constants import LimitedPrecisionConstant
1273
sage: a = LimitedPrecisionConstant('a', '1.234567891011121314').expression(); a
1274
a
1275
sage: RDF(a)
1276
1.23456789101
1277
sage: RealField(200)(a)
1278
Traceback (most recent call last):
1279
...
1280
NotImplementedError: a is only available up to 59 bits
1281
"""
1282
self._value = value
1283
self._bits = len(self._value)*3-1 #FIXME
1284
Constant.__init__(self, name, **kwds)
1285
1286
def _mpfr_(self, R):
1287
"""
1288
EXAMPLES::
1289
1290
sage: RealField(41)(brun)
1291
1.90216058310
1292
sage: RealField(20000)(brun)
1293
Traceback (most recent call last):
1294
...
1295
NotImplementedError: brun is only available up to 41 bits
1296
"""
1297
if R.precision() <= self._bits:
1298
return R(self._value)
1299
raise NotImplementedError, "%s is only available up to %s bits"%(self.name(), self._bits)
1300
1301
def _real_double_(self, R):
1302
"""
1303
EXAMPLES::
1304
1305
sage: from sage.symbolic.constants import LimitedPrecisionConstant
1306
sage: a = LimitedPrecisionConstant('a', '1.234567891011121314').expression()
1307
sage: RDF(a)
1308
1.23456789101
1309
"""
1310
if R.precision() <= self._bits:
1311
return R(self._value)
1312
raise NotImplementedError, "%s is only available up to %s bits"%(self.name(), self._bits)
1313
1314
def __float__(self):
1315
"""
1316
EXAMPLES::
1317
1318
sage: from sage.symbolic.constants import LimitedPrecisionConstant
1319
sage: a = LimitedPrecisionConstant('a', '1.234567891011121314').expression()
1320
sage: float(a)
1321
1.2345678910111213
1322
1323
"""
1324
if self._bits < 53:
1325
raise NotImplementedError, "%s is only available up to %s bits"%(self.name(), self._bits)
1326
return float(self._value)
1327
1328
class Brun(LimitedPrecisionConstant):
1329
"""
1330
Brun's constant is the sum of reciprocals of odd twin primes.
1331
1332
It is not known to very high precision; calculating the number
1333
using twin primes up to `10^{16}` (Sebah 2002) gives the
1334
number `1.9021605831040`.
1335
1336
EXAMPLES::
1337
1338
sage: float(brun)
1339
Traceback (most recent call last):
1340
...
1341
NotImplementedError: brun is only available up to 41 bits
1342
sage: R = RealField(41); R
1343
Real Field with 41 bits of precision
1344
sage: R(brun)
1345
1.90216058310
1346
"""
1347
def __init__(self, name='brun'):
1348
"""
1349
EXAMPLES::
1350
1351
sage: loads(dumps(brun))
1352
brun
1353
"""
1354
conversions = dict(maxima='brun')
1355
1356
# digits come from Sloane's tables at http://oeis.org/classic/table?a=65421&fmt=0
1357
value = "1.902160583104"
1358
1359
LimitedPrecisionConstant.__init__(self, name, value,
1360
conversions=conversions,
1361
domain='positive')
1362
1363
brun = Brun().expression()
1364
1365