-
-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
trigonometric.py
2962 lines (2384 loc) · 86.3 KB
/
trigonometric.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
from __future__ import print_function, division
from sympy.core.add import Add
from sympy.core.basic import sympify, cacheit
from sympy.core.function import Function, ArgumentIndexError
from sympy.core.numbers import igcdex, Rational, pi
from sympy.core.singleton import S
from sympy.core.symbol import Symbol, Wild
from sympy.core.logic import fuzzy_not, fuzzy_or
from sympy.functions.combinatorial.factorials import factorial, RisingFactorial
from sympy.functions.elementary.miscellaneous import sqrt, Min, Max
from sympy.functions.elementary.exponential import log, exp
from sympy.functions.elementary.integers import floor
from sympy.functions.elementary.hyperbolic import (acoth, asinh, atanh, cosh,
coth, HyperbolicFunction, sinh, tanh)
from sympy.sets.sets import FiniteSet
from sympy.utilities.iterables import numbered_symbols
from sympy.core.compatibility import range
from sympy.core.relational import Ne
from sympy.functions.elementary.piecewise import Piecewise
###############################################################################
########################## TRIGONOMETRIC FUNCTIONS ############################
###############################################################################
class TrigonometricFunction(Function):
"""Base class for trigonometric functions. """
unbranched = True
def _eval_is_rational(self):
s = self.func(*self.args)
if s.func == self.func:
if s.args[0].is_rational and fuzzy_not(s.args[0].is_zero):
return False
else:
return s.is_rational
def _eval_is_algebraic(self):
s = self.func(*self.args)
if s.func == self.func:
if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic:
return False
pi_coeff = _pi_coeff(self.args[0])
if pi_coeff is not None and pi_coeff.is_rational:
return True
else:
return s.is_algebraic
def _eval_expand_complex(self, deep=True, **hints):
re_part, im_part = self.as_real_imag(deep=deep, **hints)
return re_part + im_part*S.ImaginaryUnit
def _as_real_imag(self, deep=True, **hints):
if self.args[0].is_real:
if deep:
hints['complex'] = False
return (self.args[0].expand(deep, **hints), S.Zero)
else:
return (self.args[0], S.Zero)
if deep:
re, im = self.args[0].expand(deep, **hints).as_real_imag()
else:
re, im = self.args[0].as_real_imag()
return (re, im)
def _period(self, general_period, symbol=None):
f = self.args[0]
if symbol is None:
symbol = tuple(f.free_symbols)[0]
if not f.has(symbol):
return S.Zero
if f == symbol:
return general_period
if symbol in f.free_symbols:
p, q = Wild('p'), Wild('q')
if f.is_Mul:
g, h = f.as_independent(symbol)
if h == symbol:
return general_period/abs(g)
if f.is_Add:
a, h = f.as_independent(symbol)
g, h = h.as_independent(symbol, as_Add=False)
if h == symbol:
return general_period/abs(g)
raise NotImplementedError("Use the periodicity function instead.")
def _peeloff_pi(arg):
"""
Split ARG into two parts, a "rest" and a multiple of pi/2.
This assumes ARG to be an Add.
The multiple of pi returned in the second position is always a Rational.
Examples
========
>>> from sympy.functions.elementary.trigonometric import _peeloff_pi as peel
>>> from sympy import pi
>>> from sympy.abc import x, y
>>> peel(x + pi/2)
(x, pi/2)
>>> peel(x + 2*pi/3 + pi*y)
(x + pi*y + pi/6, pi/2)
"""
for a in Add.make_args(arg):
if a is S.Pi:
K = S.One
break
elif a.is_Mul:
K, p = a.as_two_terms()
if p is S.Pi and K.is_Rational:
break
else:
return arg, S.Zero
m1 = (K % S.Half) * S.Pi
m2 = K*S.Pi - m1
return arg - m2, m2
def _pi_coeff(arg, cycles=1):
"""
When arg is a Number times pi (e.g. 3*pi/2) then return the Number
normalized to be in the range [0, 2], else None.
When an even multiple of pi is encountered, if it is multiplying
something with known parity then the multiple is returned as 0 otherwise
as 2.
Examples
========
>>> from sympy.functions.elementary.trigonometric import _pi_coeff as coeff
>>> from sympy import pi, Dummy
>>> from sympy.abc import x, y
>>> coeff(3*x*pi)
3*x
>>> coeff(11*pi/7)
11/7
>>> coeff(-11*pi/7)
3/7
>>> coeff(4*pi)
0
>>> coeff(5*pi)
1
>>> coeff(5.0*pi)
1
>>> coeff(5.5*pi)
3/2
>>> coeff(2 + pi)
>>> coeff(2*Dummy(integer=True)*pi)
2
>>> coeff(2*Dummy(even=True)*pi)
0
"""
arg = sympify(arg)
if arg is S.Pi:
return S.One
elif not arg:
return S.Zero
elif arg.is_Mul:
cx = arg.coeff(S.Pi)
if cx:
c, x = cx.as_coeff_Mul() # pi is not included as coeff
if c.is_Float:
# recast exact binary fractions to Rationals
f = abs(c) % 1
if f != 0:
p = -int(round(log(f, 2).evalf()))
m = 2**p
cm = c*m
i = int(cm)
if i == cm:
c = Rational(i, m)
cx = c*x
else:
c = Rational(int(c))
cx = c*x
if x.is_integer:
c2 = c % 2
if c2 == 1:
return x
elif not c2:
if x.is_even is not None: # known parity
return S.Zero
return S(2)
else:
return c2*x
return cx
class sin(TrigonometricFunction):
"""
The sine function.
Returns the sine of x (measured in radians).
Notes
=====
This function will evaluate automatically in the
case x/pi is some rational number [4]_. For example,
if x is a multiple of pi, pi/2, pi/3, pi/4 and pi/6.
Examples
========
>>> from sympy import sin, pi
>>> from sympy.abc import x
>>> sin(x**2).diff(x)
2*x*cos(x**2)
>>> sin(1).diff(x)
0
>>> sin(pi)
0
>>> sin(pi/2)
1
>>> sin(pi/6)
1/2
>>> sin(pi/12)
-sqrt(2)/4 + sqrt(6)/4
See Also
========
csc, cos, sec, tan, cot
asin, acsc, acos, asec, atan, acot, atan2
References
==========
.. [1] http://en.wikipedia.org/wiki/Trigonometric_functions
.. [2] http://dlmf.nist.gov/4.14
.. [3] http://functions.wolfram.com/ElementaryFunctions/Sin
.. [4] http://mathworld.wolfram.com/TrigonometryAngles.html
"""
def period(self, symbol=None):
return self._period(2*pi, symbol)
def fdiff(self, argindex=1):
if argindex == 1:
return cos(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
from sympy.calculus import AccumBounds
from sympy.sets.setexpr import SetExpr
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Zero:
return S.Zero
elif arg is S.Infinity or arg is S.NegativeInfinity:
return AccumBounds(-1, 1)
if arg is S.ComplexInfinity:
return S.NaN
if isinstance(arg, AccumBounds):
min, max = arg.min, arg.max
d = floor(min/(2*S.Pi))
if min is not S.NegativeInfinity:
min = min - d*2*S.Pi
if max is not S.Infinity:
max = max - d*2*S.Pi
if AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, 5*S.Pi/2)) \
is not S.EmptySet and \
AccumBounds(min, max).intersection(FiniteSet(3*S.Pi/2,
7*S.Pi/2)) is not S.EmptySet:
return AccumBounds(-1, 1)
elif AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, 5*S.Pi/2)) \
is not S.EmptySet:
return AccumBounds(Min(sin(min), sin(max)), 1)
elif AccumBounds(min, max).intersection(FiniteSet(3*S.Pi/2, 8*S.Pi/2)) \
is not S.EmptySet:
return AccumBounds(-1, Max(sin(min), sin(max)))
else:
return AccumBounds(Min(sin(min), sin(max)),
Max(sin(min), sin(max)))
elif isinstance(arg, SetExpr):
return arg._eval_func(cls)
if arg.could_extract_minus_sign():
return -cls(-arg)
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return S.ImaginaryUnit * sinh(i_coeff)
pi_coeff = _pi_coeff(arg)
if pi_coeff is not None:
if pi_coeff.is_integer:
return S.Zero
if (2*pi_coeff).is_integer:
if pi_coeff.is_even:
return S.Zero
elif pi_coeff.is_even is False:
return S.NegativeOne**(pi_coeff - S.Half)
if not pi_coeff.is_Rational:
narg = pi_coeff*S.Pi
if narg != arg:
return cls(narg)
return None
# https://github.com/sympy/sympy/issues/6048
# transform a sine to a cosine, to avoid redundant code
if pi_coeff.is_Rational:
x = pi_coeff % 2
if x > 1:
return -cls((x % 1)*S.Pi)
if 2*x > 1:
return cls((1 - x)*S.Pi)
narg = ((pi_coeff + Rational(3, 2)) % 2)*S.Pi
result = cos(narg)
if not isinstance(result, cos):
return result
if pi_coeff*S.Pi != arg:
return cls(pi_coeff*S.Pi)
return None
if arg.is_Add:
x, m = _peeloff_pi(arg)
if m:
return sin(m)*cos(x) + cos(m)*sin(x)
if isinstance(arg, asin):
return arg.args[0]
if isinstance(arg, atan):
x = arg.args[0]
return x / sqrt(1 + x**2)
if isinstance(arg, atan2):
y, x = arg.args
return y / sqrt(x**2 + y**2)
if isinstance(arg, acos):
x = arg.args[0]
return sqrt(1 - x**2)
if isinstance(arg, acot):
x = arg.args[0]
return 1 / (sqrt(1 + 1 / x**2) * x)
if isinstance(arg, acsc):
x = arg.args[0]
return 1 / x
if isinstance(arg, asec):
x = arg.args[0]
return sqrt(1 - 1 / x**2)
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 0:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 2:
p = previous_terms[-2]
return -p * x**2 / (n*(n - 1))
else:
return (-1)**(n//2) * x**(n)/factorial(n)
def _eval_rewrite_as_exp(self, arg):
I = S.ImaginaryUnit
if isinstance(arg, TrigonometricFunction) or isinstance(arg, HyperbolicFunction):
arg = arg.func(arg.args[0]).rewrite(exp)
return (exp(arg*I) - exp(-arg*I)) / (2*I)
def _eval_rewrite_as_Pow(self, arg):
if isinstance(arg, log):
I = S.ImaginaryUnit
x = arg.args[0]
return I*x**-I / 2 - I*x**I /2
def _eval_rewrite_as_cos(self, arg):
return cos(arg - S.Pi / 2, evaluate=False)
def _eval_rewrite_as_tan(self, arg):
tan_half = tan(S.Half*arg)
return 2*tan_half/(1 + tan_half**2)
def _eval_rewrite_as_sincos(self, arg):
return sin(arg)*cos(arg)/cos(arg)
def _eval_rewrite_as_cot(self, arg):
cot_half = cot(S.Half*arg)
return 2*cot_half/(1 + cot_half**2)
def _eval_rewrite_as_pow(self, arg):
return self.rewrite(cos).rewrite(pow)
def _eval_rewrite_as_sqrt(self, arg):
return self.rewrite(cos).rewrite(sqrt)
def _eval_rewrite_as_csc(self, arg):
return 1/csc(arg)
def _eval_rewrite_as_sec(self, arg):
return 1 / sec(arg - S.Pi / 2, evaluate=False)
def _eval_rewrite_as_sinc(self, arg):
return arg*sinc(arg)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
re, im = self._as_real_imag(deep=deep, **hints)
return (sin(re)*cosh(im), cos(re)*sinh(im))
def _eval_expand_trig(self, **hints):
from sympy import expand_mul
from sympy.functions.special.polynomials import chebyshevt, chebyshevu
arg = self.args[0]
x = None
if arg.is_Add: # TODO, implement more if deep stuff here
# TODO: Do this more efficiently for more than two terms
x, y = arg.as_two_terms()
sx = sin(x, evaluate=False)._eval_expand_trig()
sy = sin(y, evaluate=False)._eval_expand_trig()
cx = cos(x, evaluate=False)._eval_expand_trig()
cy = cos(y, evaluate=False)._eval_expand_trig()
return sx*cy + sy*cx
else:
n, x = arg.as_coeff_Mul(rational=True)
if n.is_Integer: # n will be positive because of .eval
# canonicalization
# See http://mathworld.wolfram.com/Multiple-AngleFormulas.html
if n.is_odd:
return (-1)**((n - 1)/2)*chebyshevt(n, sin(x))
else:
return expand_mul((-1)**(n/2 - 1)*cos(x)*chebyshevu(n -
1, sin(x)), deep=False)
pi_coeff = _pi_coeff(arg)
if pi_coeff is not None:
if pi_coeff.is_Rational:
return self.rewrite(sqrt)
return sin(arg)
def _eval_as_leading_term(self, x):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return arg
else:
return self.func(arg)
def _eval_is_real(self):
if self.args[0].is_real:
return True
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_real:
return True
class cos(TrigonometricFunction):
"""
The cosine function.
Returns the cosine of x (measured in radians).
Notes
=====
See :func:`sin` for notes about automatic evaluation.
Examples
========
>>> from sympy import cos, pi
>>> from sympy.abc import x
>>> cos(x**2).diff(x)
-2*x*sin(x**2)
>>> cos(1).diff(x)
0
>>> cos(pi)
-1
>>> cos(pi/2)
0
>>> cos(2*pi/3)
-1/2
>>> cos(pi/12)
sqrt(2)/4 + sqrt(6)/4
See Also
========
sin, csc, sec, tan, cot
asin, acsc, acos, asec, atan, acot, atan2
References
==========
.. [1] http://en.wikipedia.org/wiki/Trigonometric_functions
.. [2] http://dlmf.nist.gov/4.14
.. [3] http://functions.wolfram.com/ElementaryFunctions/Cos
"""
def period(self, symbol=None):
return self._period(2*pi, symbol)
def fdiff(self, argindex=1):
if argindex == 1:
return -sin(self.args[0])
else:
raise ArgumentIndexError(self, argindex)
@classmethod
def eval(cls, arg):
from sympy.functions.special.polynomials import chebyshevt
from sympy.calculus.util import AccumBounds
from sympy.sets.setexpr import SetExpr
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Zero:
return S.One
elif arg is S.Infinity or arg is S.NegativeInfinity:
# In this case it is better to return AccumBounds(-1, 1)
# rather than returning S.NaN, since AccumBounds(-1, 1)
# preserves the information that sin(oo) is between
# -1 and 1, where S.NaN does not do that.
return AccumBounds(-1, 1)
if arg is S.ComplexInfinity:
return S.NaN
if isinstance(arg, AccumBounds):
return sin(arg + S.Pi/2)
elif isinstance(arg, SetExpr):
return arg._eval_func(cls)
if arg.could_extract_minus_sign():
return cls(-arg)
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return cosh(i_coeff)
pi_coeff = _pi_coeff(arg)
if pi_coeff is not None:
if pi_coeff.is_integer:
return (S.NegativeOne)**pi_coeff
if (2*pi_coeff).is_integer:
if pi_coeff.is_even:
return (S.NegativeOne)**(pi_coeff/2)
elif pi_coeff.is_even is False:
return S.Zero
if not pi_coeff.is_Rational:
narg = pi_coeff*S.Pi
if narg != arg:
return cls(narg)
return None
# cosine formula #####################
# https://github.com/sympy/sympy/issues/6048
# explicit calculations are preformed for
# cos(k pi/n) for n = 8,10,12,15,20,24,30,40,60,120
# Some other exact values like cos(k pi/240) can be
# calculated using a partial-fraction decomposition
# by calling cos( X ).rewrite(sqrt)
cst_table_some = {
3: S.Half,
5: (sqrt(5) + 1)/4,
}
if pi_coeff.is_Rational:
q = pi_coeff.q
p = pi_coeff.p % (2*q)
if p > q:
narg = (pi_coeff - 1)*S.Pi
return -cls(narg)
if 2*p > q:
narg = (1 - pi_coeff)*S.Pi
return -cls(narg)
# If nested sqrt's are worse than un-evaluation
# you can require q to be in (1, 2, 3, 4, 6, 12)
# q <= 12, q=15, q=20, q=24, q=30, q=40, q=60, q=120 return
# expressions with 2 or fewer sqrt nestings.
table2 = {
12: (3, 4),
20: (4, 5),
30: (5, 6),
15: (6, 10),
24: (6, 8),
40: (8, 10),
60: (20, 30),
120: (40, 60)
}
if q in table2:
a, b = p*S.Pi/table2[q][0], p*S.Pi/table2[q][1]
nvala, nvalb = cls(a), cls(b)
if None == nvala or None == nvalb:
return None
return nvala*nvalb + cls(S.Pi/2 - a)*cls(S.Pi/2 - b)
if q > 12:
return None
if q in cst_table_some:
cts = cst_table_some[pi_coeff.q]
return chebyshevt(pi_coeff.p, cts).expand()
if 0 == q % 2:
narg = (pi_coeff*2)*S.Pi
nval = cls(narg)
if None == nval:
return None
x = (2*pi_coeff + 1)/2
sign_cos = (-1)**((-1 if x < 0 else 1)*int(abs(x)))
return sign_cos*sqrt( (1 + nval)/2 )
return None
if arg.is_Add:
x, m = _peeloff_pi(arg)
if m:
return cos(m)*cos(x) - sin(m)*sin(x)
if isinstance(arg, acos):
return arg.args[0]
if isinstance(arg, atan):
x = arg.args[0]
return 1 / sqrt(1 + x**2)
if isinstance(arg, atan2):
y, x = arg.args
return x / sqrt(x**2 + y**2)
if isinstance(arg, asin):
x = arg.args[0]
return sqrt(1 - x ** 2)
if isinstance(arg, acot):
x = arg.args[0]
return 1 / sqrt(1 + 1 / x**2)
if isinstance(arg, acsc):
x = arg.args[0]
return sqrt(1 - 1 / x**2)
if isinstance(arg, asec):
x = arg.args[0]
return 1 / x
@staticmethod
@cacheit
def taylor_term(n, x, *previous_terms):
if n < 0 or n % 2 == 1:
return S.Zero
else:
x = sympify(x)
if len(previous_terms) > 2:
p = previous_terms[-2]
return -p * x**2 / (n*(n - 1))
else:
return (-1)**(n//2)*x**(n)/factorial(n)
def _eval_rewrite_as_exp(self, arg):
I = S.ImaginaryUnit
if isinstance(arg, TrigonometricFunction) or isinstance(arg, HyperbolicFunction):
arg = arg.func(arg.args[0]).rewrite(exp)
return (exp(arg*I) + exp(-arg*I)) / 2
def _eval_rewrite_as_Pow(self, arg):
if isinstance(arg, log):
I = S.ImaginaryUnit
x = arg.args[0]
return x**I/2 + x**-I/2
def _eval_rewrite_as_sin(self, arg):
return sin(arg + S.Pi / 2, evaluate=False)
def _eval_rewrite_as_tan(self, arg):
tan_half = tan(S.Half*arg)**2
return (1 - tan_half)/(1 + tan_half)
def _eval_rewrite_as_sincos(self, arg):
return sin(arg)*cos(arg)/sin(arg)
def _eval_rewrite_as_cot(self, arg):
cot_half = cot(S.Half*arg)**2
return (cot_half - 1)/(cot_half + 1)
def _eval_rewrite_as_pow(self, arg):
return self._eval_rewrite_as_sqrt(arg)
def _eval_rewrite_as_sqrt(self, arg):
from sympy.functions.special.polynomials import chebyshevt
def migcdex(x):
# recursive calcuation of gcd and linear combination
# for a sequence of integers.
# Given (x1, x2, x3)
# Returns (y1, y1, y3, g)
# such that g is the gcd and x1*y1+x2*y2+x3*y3 - g = 0
# Note, that this is only one such linear combination.
if len(x) == 1:
return (1, x[0])
if len(x) == 2:
return igcdex(x[0], x[-1])
g = migcdex(x[1:])
u, v, h = igcdex(x[0], g[-1])
return tuple([u] + [v*i for i in g[0:-1] ] + [h])
def ipartfrac(r, factors=None):
from sympy.ntheory import factorint
if isinstance(r, int):
return r
if not isinstance(r, Rational):
raise TypeError("r is not rational")
n = r.q
if 2 > r.q*r.q:
return r.q
if None == factors:
a = [n//x**y for x, y in factorint(r.q).items()]
else:
a = [n//x for x in factors]
if len(a) == 1:
return [ r ]
h = migcdex(a)
ans = [ r.p*Rational(i*j, r.q) for i, j in zip(h[:-1], a) ]
assert r == sum(ans)
return ans
pi_coeff = _pi_coeff(arg)
if pi_coeff is None:
return None
if pi_coeff.is_integer:
# it was unevaluated
return self.func(pi_coeff*S.Pi)
if not pi_coeff.is_Rational:
return None
def _cospi257():
""" Express cos(pi/257) explicitly as a function of radicals
Based upon the equations in
http://math.stackexchange.com/questions/516142/how-does-cos2-pi-257-look-like-in-real-radicals
See also http://www.susqu.edu/brakke/constructions/257-gon.m.txt
"""
def f1(a, b):
return (a + sqrt(a**2 + b))/2, (a - sqrt(a**2 + b))/2
def f2(a, b):
return (a - sqrt(a**2 + b))/2
t1, t2 = f1(-1, 256)
z1, z3 = f1(t1, 64)
z2, z4 = f1(t2, 64)
y1, y5 = f1(z1, 4*(5 + t1 + 2*z1))
y6, y2 = f1(z2, 4*(5 + t2 + 2*z2))
y3, y7 = f1(z3, 4*(5 + t1 + 2*z3))
y8, y4 = f1(z4, 4*(5 + t2 + 2*z4))
x1, x9 = f1(y1, -4*(t1 + y1 + y3 + 2*y6))
x2, x10 = f1(y2, -4*(t2 + y2 + y4 + 2*y7))
x3, x11 = f1(y3, -4*(t1 + y3 + y5 + 2*y8))
x4, x12 = f1(y4, -4*(t2 + y4 + y6 + 2*y1))
x5, x13 = f1(y5, -4*(t1 + y5 + y7 + 2*y2))
x6, x14 = f1(y6, -4*(t2 + y6 + y8 + 2*y3))
x15, x7 = f1(y7, -4*(t1 + y7 + y1 + 2*y4))
x8, x16 = f1(y8, -4*(t2 + y8 + y2 + 2*y5))
v1 = f2(x1, -4*(x1 + x2 + x3 + x6))
v2 = f2(x2, -4*(x2 + x3 + x4 + x7))
v3 = f2(x8, -4*(x8 + x9 + x10 + x13))
v4 = f2(x9, -4*(x9 + x10 + x11 + x14))
v5 = f2(x10, -4*(x10 + x11 + x12 + x15))
v6 = f2(x16, -4*(x16 + x1 + x2 + x5))
u1 = -f2(-v1, -4*(v2 + v3))
u2 = -f2(-v4, -4*(v5 + v6))
w1 = -2*f2(-u1, -4*u2)
return sqrt(sqrt(2)*sqrt(w1 + 4)/8 + S.Half)
cst_table_some = {
3: S.Half,
5: (sqrt(5) + 1)/4,
17: sqrt((15 + sqrt(17))/32 + sqrt(2)*(sqrt(17 - sqrt(17)) +
sqrt(sqrt(2)*(-8*sqrt(17 + sqrt(17)) - (1 - sqrt(17))
*sqrt(17 - sqrt(17))) + 6*sqrt(17) + 34))/32),
257: _cospi257()
# 65537 is the only other known Fermat prime and the very
# large expression is intentionally omitted from SymPy; see
# http://www.susqu.edu/brakke/constructions/65537-gon.m.txt
}
def _fermatCoords(n):
# if n can be factored in terms of Fermat primes with
# multiplicity of each being 1, return those primes, else
# False
primes = []
for p_i in cst_table_some:
quotient, remainder = divmod(n, p_i)
if remainder == 0:
n = quotient
primes.append(p_i)
if n == 1:
return tuple(primes)
return False
if pi_coeff.q in cst_table_some:
rv = chebyshevt(pi_coeff.p, cst_table_some[pi_coeff.q])
if pi_coeff.q < 257:
rv = rv.expand()
return rv
if not pi_coeff.q % 2: # recursively remove factors of 2
pico2 = pi_coeff*2
nval = cos(pico2*S.Pi).rewrite(sqrt)
x = (pico2 + 1)/2
sign_cos = -1 if int(x) % 2 else 1
return sign_cos*sqrt( (1 + nval)/2 )
FC = _fermatCoords(pi_coeff.q)
if FC:
decomp = ipartfrac(pi_coeff, FC)
X = [(x[1], x[0]*S.Pi) for x in zip(decomp, numbered_symbols('z'))]
pcls = cos(sum([x[0] for x in X]))._eval_expand_trig().subs(X)
return pcls.rewrite(sqrt)
else:
decomp = ipartfrac(pi_coeff)
X = [(x[1], x[0]*S.Pi) for x in zip(decomp, numbered_symbols('z'))]
pcls = cos(sum([x[0] for x in X]))._eval_expand_trig().subs(X)
return pcls
def _eval_rewrite_as_sec(self, arg):
return 1/sec(arg)
def _eval_rewrite_as_csc(self, arg):
return 1 / sec(arg)._eval_rewrite_as_csc(arg)
def _eval_conjugate(self):
return self.func(self.args[0].conjugate())
def as_real_imag(self, deep=True, **hints):
re, im = self._as_real_imag(deep=deep, **hints)
return (cos(re)*cosh(im), -sin(re)*sinh(im))
def _eval_expand_trig(self, **hints):
from sympy.functions.special.polynomials import chebyshevt
arg = self.args[0]
x = None
if arg.is_Add: # TODO: Do this more efficiently for more than two terms
x, y = arg.as_two_terms()
sx = sin(x, evaluate=False)._eval_expand_trig()
sy = sin(y, evaluate=False)._eval_expand_trig()
cx = cos(x, evaluate=False)._eval_expand_trig()
cy = cos(y, evaluate=False)._eval_expand_trig()
return cx*cy - sx*sy
else:
coeff, terms = arg.as_coeff_Mul(rational=True)
if coeff.is_Integer:
return chebyshevt(coeff, cos(terms))
pi_coeff = _pi_coeff(arg)
if pi_coeff is not None:
if pi_coeff.is_Rational:
return self.rewrite(sqrt)
return cos(arg)
def _eval_as_leading_term(self, x):
from sympy import Order
arg = self.args[0].as_leading_term(x)
if x in arg.free_symbols and Order(1, x).contains(arg):
return S.One
else:
return self.func(arg)
def _eval_is_real(self):
if self.args[0].is_real:
return True
def _eval_is_finite(self):
arg = self.args[0]
if arg.is_real:
return True
class tan(TrigonometricFunction):
"""
The tangent function.
Returns the tangent of x (measured in radians).
Notes
=====
See :func:`sin` for notes about automatic evaluation.
Examples
========
>>> from sympy import tan, pi
>>> from sympy.abc import x
>>> tan(x**2).diff(x)
2*x*(tan(x**2)**2 + 1)
>>> tan(1).diff(x)
0
>>> tan(pi/8).expand()
-1 + sqrt(2)
See Also
========
sin, csc, cos, sec, cot
asin, acsc, acos, asec, atan, acot, atan2
References
==========
.. [1] http://en.wikipedia.org/wiki/Trigonometric_functions
.. [2] http://dlmf.nist.gov/4.14
.. [3] http://functions.wolfram.com/ElementaryFunctions/Tan
"""
def period(self, symbol=None):
return self._period(pi, symbol)
def fdiff(self, argindex=1):
if argindex == 1:
return S.One + self**2
else:
raise ArgumentIndexError(self, argindex)
def inverse(self, argindex=1):
"""
Returns the inverse of this function.
"""
return atan
@classmethod
def eval(cls, arg):
from sympy.calculus.util import AccumBounds
if arg.is_Number:
if arg is S.NaN:
return S.NaN
elif arg is S.Zero:
return S.Zero
elif arg is S.Infinity or arg is S.NegativeInfinity:
return AccumBounds(S.NegativeInfinity, S.Infinity)
if arg is S.ComplexInfinity:
return S.NaN
if isinstance(arg, AccumBounds):
min, max = arg.min, arg.max
d = floor(min/S.Pi)
if min is not S.NegativeInfinity:
min = min - d*S.Pi
if max is not S.Infinity:
max = max - d*S.Pi
if AccumBounds(min, max).intersection(FiniteSet(S.Pi/2, 3*S.Pi/2)):
return AccumBounds(S.NegativeInfinity, S.Infinity)
else:
return AccumBounds(tan(min), tan(max))
if arg.could_extract_minus_sign():
return -cls(-arg)
i_coeff = arg.as_coefficient(S.ImaginaryUnit)
if i_coeff is not None:
return S.ImaginaryUnit * tanh(i_coeff)
pi_coeff = _pi_coeff(arg, 2)
if pi_coeff is not None:
if pi_coeff.is_integer:
return S.Zero
if not pi_coeff.is_Rational:
narg = pi_coeff*S.Pi
if narg != arg:
return cls(narg)
return None