-
-
Notifications
You must be signed in to change notification settings - Fork 396
/
library.py
1731 lines (1484 loc) · 71.3 KB
/
library.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
"""
Sage Interacts
Sage interacts are applications of the `@interact decorator <../../sagenb/notebook/interact.html>`_.
They are conveniently accessible in the Sage Notebook via ``interacts.[TAB].[TAB]()``.
The first ``[TAB]`` lists categories and the second ``[TAB]`` reveals the interact examples.
EXAMPLES:
Invoked in the notebook, the following command will produce the fully formatted
interactive mathlet. In the command line, it will simply return the underlying
HTML and Sage code which creates the mathlet::
sage: interacts.calculus.taylor_polynomial()
Interactive function <function taylor_polynomial at ...> with 3 widgets
title: HTMLText(value=u'<h2>Taylor polynomial</h2>')
f: EvalText(value=u'e^(-x)*sin(x)', description=u'$f(x)=$', layout=Layout(max_width=u'81em'))
order: SelectionSlider(description=u'order', options=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), value=1)
AUTHORS:
- William Stein
- Harald Schilly, Robert Marik (2011-01-16): added many examples (#9623) partially based on work by Lauri Ruotsalainen
"""
#*****************************************************************************
# Copyright (C) 2009 William Stein <wstein@gmail.com>
# Copyright (C) 2011 Harald Schilly <harald.schilly@gmail.com>
#
# Distributed under the terms of the GNU General Public License (GPL)
# as published by the Free Software Foundation; either version 2 of
# the License, or (at your option) any later version.
# http://www.gnu.org/licenses/
#*****************************************************************************
from __future__ import absolute_import, division
from sage.all import *
x = SR.var('x')
# It is important that this file is lazily imported for this to work
from sage.repl.user_globals import get_global
# Get a bunch of functions from the user globals. In SageNB, this will
# refer to SageNB functions; in Jupyter, this will refer to Jupyter
# functions. In the command-line and for doctests, we import the
# SageNB functions as fall-back.
for name in ("interact", "checkbox", "input_box", "input_grid",
"range_slider", "selector", "slider", "text_control"):
try:
obj = get_global(name)
except NameError:
import sagenb.notebook.interact
obj = sagenb.notebook.interact.__dict__[name]
globals()[name] = obj
def library_interact(f):
"""
This is a decorator for using interacts in the Sage library.
This is just the ``interact`` function wrapped in an additional
function call: ``library_interact(f)()`` is equivalent to
executing ``interact(f)``.
EXAMPLES::
sage: import sage.interacts.library as library
sage: @library.library_interact
....: def f(n=5):
....: print(n)
sage: f() # an interact appears if using the notebook, else code
Interactive function <function f at ...> with 1 widget
n: IntSlider(value=5, description=u'n', max=15, min=-5)
"""
@sage_wraps(f)
def library_wrapper():
# This will display the interact, no need to return anything
interact(f)
return library_wrapper
def html(obj):
"""
Shorthand to pretty print HTML
EXAMPLES::
sage: from sage.interacts.library import html
sage: html("<h1>Hello world</h1>")
<h1>Hello world</h1>
"""
from sage.all import html
pretty_print(html(obj))
@library_interact
def demo(n=slider(range(10)), m=slider(range(10))):
"""
This is a demo interact that sums two numbers.
INPUT:
- ``n`` -- integer slider
- ``m`` -- integer slider
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.demo()
Interactive function <function demo at ...> with 2 widgets
n: SelectionSlider(description=u'n', options=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), value=0)
m: SelectionSlider(description=u'm', options=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), value=0)
"""
print(n + m)
@library_interact
def taylor_polynomial(
title = text_control('<h2>Taylor polynomial</h2>'),
f=input_box(sin(x)*exp(-x),label="$f(x)=$"), order=slider(range(1,13))):
"""
An interact which illustrates the Taylor polynomial approximation
of various orders around `x=0`.
- ``f`` -- function expression
- ```order``` -- integer slider
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.calculus.taylor_polynomial()
Interactive function <function taylor_polynomial at ...> with 3 widgets
title: HTMLText(value=u'<h2>Taylor polynomial</h2>')
f: EvalText(value=u'e^(-x)*sin(x)', description=u'$f(x)=$', layout=Layout(max_width=u'81em'))
order: SelectionSlider(description=u'order', options=(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12), value=1)
"""
x0 = 0
p = plot(f,(x,-1,5), thickness=2)
dot = point((x0,f(x=x0)),pointsize=80,rgbcolor=(1,0,0))
ft = f.taylor(x,x0,order)
pt = plot(ft,(-1, 5), color='green', thickness=2)
html(r'$f(x)\;=\;%s$' % latex(f))
html(r'$\hat{f}(x;%s)\;=\;%s+\mathcal{O}(x^{%s})$' % (x0, latex(ft),
order + 1))
show(dot + p + pt, ymin = -.5, ymax = 1)
@library_interact
def definite_integral(
title = text_control('<h2>Definite integral</h2>'),
f = input_box(default = "3*x", label = '$f(x)=$'),
g = input_box(default = "x^2", label = '$g(x)=$'),
interval = range_slider(-10,10,default=(0,3), label="Interval"),
x_range = range_slider(-10,10,default=(0,3), label = "plot range (x)"),
selection = selector(["f", "g", "f and g", "f - g"], default="f and g", label="Select")):
"""
This is a demo interact for plotting the definite integral of a function
based on work by Lauri Ruotsalainen, 2010.
INPUT:
- ``function`` -- input box, function in x
- ``interval`` -- interval for the definite integral
- ``x_range`` -- range slider for plotting range
- ``selection`` -- selector on how to visualize the integrals
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.calculus.definite_integral()
Interactive function <function definite_integral at ...> with 6 widgets
title: HTMLText(value=u'<h2>Definite integral</h2>')
f: EvalText(value=u'3*x', description=u'$f(x)=$', layout=Layout(max_width=u'81em'))
g: EvalText(value=u'x^2', description=u'$g(x)=$', layout=Layout(max_width=u'81em'))
interval: IntRangeSlider(value=(0, 3), description=u'Interval', max=10, min=-10)
x_range: IntRangeSlider(value=(0, 3), description=u'plot range (x)', max=10, min=-10)
selection: Dropdown(description=u'Select', index=2, options=('f', 'g', 'f and g', 'f - g'), value='f and g')
"""
x = SR.var('x')
f = symbolic_expression(f).function(x)
g = symbolic_expression(g).function(x)
f_plot = Graphics(); g_plot = Graphics(); h_plot = Graphics();
text = ""
# Plot function f.
if selection != "g":
f_plot = plot(f(x), x, x_range, color="blue", thickness=1.5)
# Color and calculate the area between f and the horizontal axis.
if selection == "f" or selection == "f and g":
f_plot += plot(f(x), x, interval, color="blue", fill=True, fillcolor="blue", fillalpha=0.15)
text += r"$\int_{%.2f}^{%.2f}(\color{Blue}{f(x)})\,\mathrm{d}x=\int_{%.2f}^{%.2f}(%s)\,\mathrm{d}x=%.2f$" % (
interval[0], interval[1],
interval[0], interval[1],
latex(f(x)),
f(x).nintegrate(x, interval[0], interval[1])[0]
)
if selection == "f and g":
text += r"<br/>"
# Plot function g. Also color and calculate the area between g and the horizontal axis.
if selection == "g" or selection == "f and g":
g_plot = plot(g(x), x, x_range, color="green", thickness=1.5)
g_plot += plot(g(x), x, interval, color="green", fill=True, fillcolor="yellow", fillalpha=0.5)
text += r"$\int_{%.2f}^{%.2f}(\color{Green}{g(x)})\,\mathrm{d}x=\int_{%.2f}^{%.2f}(%s)\,\mathrm{d}x=%.2f$" % (
interval[0], interval[1],
interval[0], interval[1],
latex(g(x)),
g(x).nintegrate(x, interval[0], interval[1])[0]
)
# Plot function f-g. Also color and calculate the area between f-g and the horizontal axis.
if selection == "f - g":
g_plot = plot(g(x), x, x_range, color="green", thickness=1.5)
g_plot += plot(g(x), x, interval, color="green", fill=f(x), fillcolor="red", fillalpha=0.15)
h_plot = plot(f(x)-g(x), x, interval, color="red", thickness=1.5, fill=True, fillcolor="red", fillalpha=0.15)
text = r"$\int_{%.2f}^{%.2f}(\color{Red}{f(x)-g(x)})\,\mathrm{d}x=\int_{%.2f}^{%.2f}(%s)\,\mathrm{d}x=%.2f$" % (
interval[0], interval[1],
interval[0], interval[1],
latex(f(x)-g(x)),
(f(x)-g(x)).nintegrate(x, interval[0], interval[1])[0]
)
show(f_plot + g_plot + h_plot, gridlines=True)
html(text)
@library_interact
def function_derivative(
title = text_control('<h2>Derivative grapher</h2>'),
function = input_box(default="x^5-3*x^3+1", label="Function:"),
x_range = range_slider(-15,15,0.1, default=(-2,2), label="Range (x)"),
y_range = range_slider(-15,15,0.1, default=(-8,6), label="Range (y)")):
"""
This is a demo interact for plotting derivatives of a function based on work by
Lauri Ruotsalainen, 2010.
INPUT:
- ``function`` -- input box, function in x
- ``x_range`` -- range slider for plotting range
- ``y_range`` -- range slider for plotting range
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.calculus.function_derivative()
Interactive function <function function_derivative at ...> with 4 widgets
title: HTMLText(value=u'<h2>Derivative grapher</h2>')
function: EvalText(value=u'x^5-3*x^3+1', description=u'Function:', layout=Layout(max_width=u'81em'))
x_range: FloatRangeSlider(value=(-2.0, 2.0), description=u'Range (x)', max=15.0, min=-15.0)
y_range: FloatRangeSlider(value=(-8.0, 6.0), description=u'Range (y)', max=15.0, min=-15.0)
"""
x = SR.var('x')
f = symbolic_expression(function).function(x)
df = derivative(f, x)
ddf = derivative(df, x)
plots = plot(f(x), x_range, thickness=1.5) + plot(df(x), x_range, color="green") + plot(ddf(x), x_range, color="red")
if y_range == (0,0):
show(plots, xmin=x_range[0], xmax=x_range[1])
else:
show(plots, xmin=x_range[0], xmax=x_range[1], ymin=y_range[0], ymax=y_range[1])
html(r"<center>$\color{Blue}{f(x) = %s}$</center>" % latex(f(x)))
html(r"<center>$\color{Green}{f'(x) = %s}$</center>" % latex(df(x)))
html(r"<center>$\color{Red}{f''(x) = %s}$</center>" % latex(ddf(x)))
@library_interact
def difference_quotient(
title = text_control('<h2>Difference quotient</h2>'),
f = input_box(default="sin(x)", label='f(x)'),
interval= range_slider(0, 10, 0.1, default=(0.0,10.0), label="Range"),
a = slider(0, 10, None, 5.5, label = '$a$'),
x0 = slider(0, 10, None, 2.5, label = '$x_0$ (start point)')):
"""
This is a demo interact for difference quotient based on work by
Lauri Ruotsalainen, 2010.
INPUT:
- ``f`` -- input box, function in `x`
- ``interval`` -- range slider for plotting
- ``a`` -- slider for `a`
- ``x0`` -- slider for starting point `x_0`
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.calculus.difference_quotient()
Interactive function <function difference_quotient at ...> with 5 widgets
title: HTMLText(value=u'<h2>Difference quotient</h2>')
f: EvalText(value=u'sin(x)', description=u'f(x)', layout=Layout(max_width=u'81em'))
interval: FloatRangeSlider(value=(0.0, 10.0), description=u'Range', max=10.0)
a: IntSlider(value=5, description=u'$a$', max=10)
x0: IntSlider(value=2, description=u'$x_0$ (start point)', max=10)
"""
html('<h2>Difference Quotient</h2>')
html('<div style="white-space: normal;">\
<a href="https://en.wikipedia.org/wiki/Difference_quotient" target="_blank">\
Wikipedia article about difference quotient</a></div>'
)
x = SR.var('x')
f = symbolic_expression(f).function(x)
fmax = f.find_local_maximum(interval[0], interval[1])[0]
fmin = f.find_local_minimum(interval[0], interval[1])[0]
f_height = fmax - fmin
measure_y = fmin - 0.1*f_height
measure_0 = line2d([(x0, measure_y), (a, measure_y)], rgbcolor="black")
measure_1 = line2d([(x0, measure_y + 0.02*f_height), (x0, measure_y-0.02*f_height)], rgbcolor="black")
measure_2 = line2d([(a, measure_y + 0.02*f_height), (a, measure_y-0.02*f_height)], rgbcolor="black")
text_x0 = text("x0", (x0, measure_y - 0.05*f_height), rgbcolor="black")
text_a = text("a", (a, measure_y - 0.05*f_height), rgbcolor="black")
measure = measure_0 + measure_1 + measure_2 + text_x0 + text_a
tanf = symbolic_expression((f(x0)-f(a))*(x-a)/(x0-a)+f(a)).function(x)
fplot = plot(f(x), x, interval[0], interval[1])
tanplot = plot(tanf(x), x, interval[0], interval[1], rgbcolor="#FF0000")
points = point([(x0, f(x0)), (a, f(a))], pointsize=20, rgbcolor="#005500")
dashline = line2d([(x0, f(x0)), (x0, f(a)), (a, f(a))], rgbcolor="#005500", linestyle="--")
html('<h2>Difference Quotient</h2>')
show(fplot + tanplot + points + dashline + measure, xmin=interval[0], xmax=interval[1], ymin=fmin-0.2*f_height, ymax=fmax)
html(r"<br>$\text{Line's equation:}$")
html(r"$y = %s$<br>"%tanf(x))
html(r"$\text{Slope:}$")
html(r"$k = \frac{f(x_0)-f(a)}{x_0-a} = %s$<br>" % (N(derivative(tanf(x), x), digits=5)))
@library_interact
def quadratic_equation(A = slider(-7, 7, 1, 1), B = slider(-7, 7, 1, 1), C = slider(-7, 7, 1, -2)):
"""
This is a demo interact for solving quadratic equations based on work by
Lauri Ruotsalainen, 2010.
INPUT:
- ``A`` -- integer slider
- ``B`` -- integer slider
- ``C`` -- integer slider
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.calculus.quadratic_equation()
Interactive function <function quadratic_equation at ...> with 3 widgets
A: IntSlider(value=1, description=u'A', max=7, min=-7)
B: IntSlider(value=1, description=u'B', max=7, min=-7)
C: IntSlider(value=-2, description=u'C', max=7, min=-7)
"""
x = SR.var('x')
f = symbolic_expression(A*x**2 + B*x + C).function(x)
html('<h2>The Solutions of the Quadratic Equation</h2>')
html("$%s = 0$" % f(x))
show(plot(f(x), x, (-10, 10), ymin=-10, ymax=10), aspect_ratio=1, figsize=4)
d = B**2 - 4*A*C
if d < 0:
color = "Red"
sol = r"\text{solution} \in \mathbb{C}"
elif d == 0:
color = "Blue"
sol = -B/(2*A)
else:
color = "Green"
a = (-B+sqrt(B**2-4*A*C))/(2*A)
b = (-B-sqrt(B**2-4*A*C))/(2*A)
sol = r"\begin{cases}%s\\%s\end{cases}" % (latex(a), latex(b))
if B < 0:
dis1 = "(%s)^2-4*%s*%s" % (B, A, C)
else:
dis1 = "%s^2-4*%s*%s" % (B, A, C)
dis2 = r"\color{%s}{%s}" % (color, d)
html("$Ax^2 + Bx + C = 0$")
calc = r"$x = \frac{-B\pm\sqrt{B^2-4AC}}{2A} = " + \
r"\frac{-%s\pm\sqrt{%s}}{2*%s} = " + \
r"\frac{-%s\pm\sqrt{%s}}{%s} = %s$"
html(calc % (B, dis1, A, B, dis2, (2*A), sol))
@library_interact
def trigonometric_properties_triangle(
a0 = slider(0, 360, 1, 30, label="A"),
a1 = slider(0, 360, 1, 180, label="B"),
a2 = slider(0, 360, 1, 300, label="C")):
"""
This is an interact for demonstrating trigonometric properties
in a triangle based on work by Lauri Ruotsalainen, 2010.
INPUT:
- ``a0`` -- angle
- ``a1`` -- angle
- ``a2`` -- angle
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.geometry.trigonometric_properties_triangle()
Interactive function <function trigonometric_properties_triangle at ...> with 3 widgets
a0: IntSlider(value=30, description=u'A', max=360)
a1: IntSlider(value=180, description=u'B', max=360)
a2: IntSlider(value=300, description=u'C', max=360)
"""
import math
# Returns the distance between points (x1,y1) and (x2,y2)
def distance(x1_y1, x2_y2):
(x1, y1) = x1_y1
(x2, y2) = x2_y2
return sqrt((x2-x1)**2 + (y2-y1)**2)
# Returns an angle (in radians) when sides a and b
# are adjacent and the side c is opposite to the angle
def angle(a, b, c):
a,b,c = map(float,[a,b,c])
return acos(0.5 * (b**2 + c**2 - a**2) / (b * c))
# Returns the area of a triangle when an angle alpha
# and adjacent sides a and b are known
def area(alpha, a, b):
return 0.5 * a * b * sin(alpha)
xy = [0]*3
html('<h2>Trigonometric Properties of a Triangle</h2>')
# Coordinates of the angles
a = [math.radians(float(x)) for x in [a0, a1, a2]]
for i in range(3):
xy[i] = (cos(a[i]), sin(a[i]))
# Side lengths (bc, ca, ab) corresponding to triangle vertices (a, b, c)
al = [distance(xy[1], xy[2]), distance(xy[2], xy[0]), distance(xy[0], xy[1])]
# The angles (a, b, c) in radians
ak = [angle(al[0], al[1], al[2]), angle(al[1], al[2], al[0]), angle(al[2], al[0], al[1])]
# The area of the triangle
A = area(ak[0], al[1], al[2])
unit_circle = circle((0, 0), 1, aspect_ratio=1)
# Triangle
triangle = line([xy[0], xy[1], xy[2], xy[0]], rgbcolor="black")
triangle_points = point(xy, pointsize=30)
# Labels of the angles drawn in a distance from points
a_label = text("A", (xy[0][0]*1.07, xy[0][1]*1.07))
b_label = text("B", (xy[1][0]*1.07, xy[1][1]*1.07))
c_label = text("C", (xy[2][0]*1.07, xy[2][1]*1.07))
labels = a_label + b_label + c_label
show(unit_circle + triangle + triangle_points + labels, figsize=[5, 5], xmin=-1, xmax=1, ymin=-1, ymax=1)
html(r"$\angle A = {%.3f}^{\circ},$ $\angle B = {%.3f}^{\circ},$ $\angle C = {%.3f}^{\circ}$"
% (math.degrees(ak[0]), math.degrees(ak[1]), math.degrees(ak[2])))
html(r"$AB = %.6f$, $BC = %.6f$, $CA = %.6f$" % (al[2], al[0], al[1]))
html(r"Area of triangle $ABC = %.6f$" % A)
@library_interact
def unit_circle(
function = selector([(0, sin(x)), (1, cos(x)), (2, tan(x))]),
x = slider(0,2*pi, 0.005*pi, 0)):
"""
This is an interact for Sin, Cos and Tan in the Unit Circle
based on work by Lauri Ruotsalainen, 2010.
INPUT:
- ``function`` -- select Sin, Cos or Tan
- ``x`` -- slider to select angle in unit circle
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.geometry.unit_circle()
Interactive function <function unit_circle at ...> with 2 widgets
function: Dropdown(description=u'function', options=(('sin(x)', 0), ('cos(x)', 1), ('tan(x)', 2)), value=0)
x: TransformFloatSlider(value=0.0, description=u'x', max=6.283185307179586, step=0.015707963267948967)
"""
xy = (cos(x), sin(x))
t = SR.var('t')
html('<div style="white-space: normal;">Lines of the same color have\
the same length</div>')
# Unit Circle
C = circle((0, 0), 1, figsize=[5, 5], aspect_ratio=1)
C_line = line([(0, 0), (xy[0], xy[1])], rgbcolor="black")
C_point = point((xy[0], xy[1]), pointsize=40, rgbcolor="green")
C_inner = parametric_plot((cos(t), sin(t)), (t, 0, x + 0.001), color="green", thickness=3)
C_outer = parametric_plot((0.1 * cos(t), 0.1 * sin(t)), (t, 0, x + 0.001), color="black")
C_graph = C + C_line + C_point + C_inner + C_outer
# Graphics related to the graph of the function
G_line = line([(0, 0), (x, 0)], rgbcolor="green", thickness=3)
G_point = point((x, 0), pointsize=30, rgbcolor="green")
G_graph = G_line + G_point
# Sine
if function == 0:
Gf = plot(sin(t), t, 0, 2*pi, axes_labels=("x", "sin(x)"))
Gf_point = point((x, sin(x)), pointsize=30, rgbcolor="red")
Gf_line = line([(x, 0),(x, sin(x))], rgbcolor="red")
Cf_point = point((0, xy[1]), pointsize=40, rgbcolor="red")
Cf_line1 = line([(0, 0), (0, xy[1])], rgbcolor="red", thickness=3)
Cf_line2 = line([(0, xy[1]), (xy[0], xy[1])], rgbcolor="purple", linestyle="--")
# Cosine
elif function == 1:
Gf = plot(cos(t), t, 0, 2*pi, axes_labels=("x", "cos(x)"))
Gf_point = point((x, cos(x)), pointsize=30, rgbcolor="red")
Gf_line = line([(x, 0), (x, cos(x))], rgbcolor="red")
Cf_point = point((xy[0], 0), pointsize=40, rgbcolor="red")
Cf_line1 = line([(0, 0), (xy[0], 0)], rgbcolor="red", thickness=3)
Cf_line2 = line([(xy[0], 0), (xy[0], xy[1])], rgbcolor="purple", linestyle="--")
# Tangent
else:
Gf = plot(tan(t), t, 0, 2*pi, ymin=-8, ymax=8, axes_labels=("x", "tan(x)"))
Gf_point = point((x, tan(x)), pointsize=30, rgbcolor="red")
Gf_line = line([(x, 0), (x, tan(x))], rgbcolor="red")
Cf_point = point((1, tan(x)), pointsize=40, rgbcolor="red")
Cf_line1 = line([(1, 0), (1, tan(x))], rgbcolor="red", thickness=3)
Cf_line2 = line([(xy[0], xy[1]), (1, tan(x))], rgbcolor="purple", linestyle="--")
C_graph += Cf_point + Cf_line1 + Cf_line2
G_graph += Gf + Gf_point + Gf_line
show(graphics_array([C_graph, G_graph]))
@library_interact
def special_points(
title = text_control('<h2>Special points in triangle</h2>'),
a0 = slider(0, 360, 1, 30, label="A"),
a1 = slider(0, 360, 1, 180, label="B"),
a2 = slider(0, 360, 1, 300, label="C"),
show_median = checkbox(False, label="Medians"),
show_pb = checkbox(False, label="Perpendicular Bisectors"),
show_alt = checkbox(False, label="Altitudes"),
show_ab = checkbox(False, label="Angle Bisectors"),
show_incircle = checkbox(False, label="Incircle"),
show_euler = checkbox(False, label="Euler's Line")):
"""
This interact demo shows special points in a triangle
based on work by Lauri Ruotsalainen, 2010.
INPUT:
- ``a0`` -- angle
- ``a1`` -- angle
- ``a2`` -- angle
- ``show_median`` -- checkbox
- ``show_pb`` -- checkbox to show perpendicular bisectors
- ``show_alt`` -- checkbox to show altitudes
- ``show_ab`` -- checkbox to show angle bisectors
- ``show_incircle`` -- checkbox to show incircle
- ``show_euler`` -- checkbox to show euler's line
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.geometry.special_points()
Interactive function <function special_points at ...> with 10 widgets
title: HTMLText(value=u'<h2>Special points in triangle</h2>')
a0: IntSlider(value=30, description=u'A', max=360)
a1: IntSlider(value=180, description=u'B', max=360)
a2: IntSlider(value=300, description=u'C', max=360)
show_median: Checkbox(value=False, description=u'Medians')
show_pb: Checkbox(value=False, description=u'Perpendicular Bisectors')
show_alt: Checkbox(value=False, description=u'Altitudes')
show_ab: Checkbox(value=False, description=u'Angle Bisectors')
show_incircle: Checkbox(value=False, description=u'Incircle')
show_euler: Checkbox(value=False, description=u"Euler's Line")
"""
import math
# Return the intersection point of the bisector of the angle <(A[a],A[c],A[b]) and the unit circle. Angles given in radians.
def half(A, a, b, c):
if (A[a] < A[b] and (A[c] < A[a] or A[c] > A[b])) or (A[a] > A[b] and (A[c] > A[a] or A[c] < A[b])):
p = A[a] + 0.5 * (A[b] - A[a])
else:
p = A[b] + 0.5 * (2*pi - (A[b]-A[a]))
return (math.cos(p), math.sin(p))
# Returns the distance between points (x1,y1) and (x2,y2)
def distance(x1_y1, x2_y2):
(x1, y1) = x1_y1
(x2, y2) = x2_y2
return math.sqrt((x2-x1)**2 + (y2-y1)**2)
# Returns the line (graph) going through points (x1,y1) and (x2,y2)
def line_to_points(x1_y1, x2_y2, **plot_kwargs):
(x1, y1) = x1_y1
(x2, y2) = x2_y2
return plot((y2-y1) / (x2-x1) * (x-x1) + y1, (x,-3,3), **plot_kwargs)
# Coordinates of the angles
a = [math.radians(float(x)) for x in [a0, a1, a2]]
xy = [(math.cos(a[i]), math.sin(a[i])) for i in range(3)]
# Labels of the angles drawn in a distance from points
a_label = text("A", (xy[0][0]*1.07, xy[0][1]*1.07))
b_label = text("B", (xy[1][0]*1.07, xy[1][1]*1.07))
c_label = text("C", (xy[2][0]*1.07, xy[2][1]*1.07))
labels = a_label + b_label + c_label
C = circle((0, 0), 1, aspect_ratio=1)
# Triangle
triangle = line([xy[0], xy[1], xy[2], xy[0]], rgbcolor="black")
triangle_points = point(xy, pointsize=30)
# Side lengths (bc, ca, ab) corresponding to triangle vertices (a, b, c)
ad = [distance(xy[1], xy[2]), distance(xy[2], xy[0]), distance(xy[0], xy[1])]
# Midpoints of edges (bc, ca, ab)
a_middle = [
(0.5 * (xy[1][0] + xy[2][0]), 0.5 * (xy[1][1] + xy[2][1])),
(0.5 * (xy[2][0] + xy[0][0]), 0.5 * (xy[2][1] + xy[0][1])),
(0.5 * (xy[0][0] + xy[1][0]), 0.5 * (xy[0][1] + xy[1][1]))
]
# Incircle
perimeter = float(ad[0] + ad[1] + ad[2])
incircle_center = (
(ad[0]*xy[0][0] + ad[1]*xy[1][0] + ad[2]*xy[2][0]) / perimeter,
(ad[0]*xy[0][1] + ad[1]*xy[1][1] + ad[2]*xy[2][1]) / perimeter
)
if show_incircle:
s = 0.5 * perimeter
incircle_r = math.sqrt((s - ad[0]) * (s - ad[1]) * (s - ad[2]) / s)
incircle_graph = circle(incircle_center, incircle_r) + point(incircle_center)
else:
incircle_graph = Graphics()
# Angle Bisectors
if show_ab:
a_ab = line([xy[0], half(a, 1, 2, 0)], rgbcolor="blue", alpha=0.6)
b_ab = line([xy[1], half(a, 2, 0, 1)], rgbcolor="blue", alpha=0.6)
c_ab = line([xy[2], half(a, 0, 1, 2)], rgbcolor="blue", alpha=0.6)
ab_point = point(incircle_center, rgbcolor="blue", pointsize=28)
ab_graph = a_ab + b_ab + c_ab + ab_point
else:
ab_graph = Graphics()
# Medians
if show_median:
a_median = line([xy[0], a_middle[0]], rgbcolor="green", alpha=0.6)
b_median = line([xy[1], a_middle[1]], rgbcolor="green", alpha=0.6)
c_median = line([xy[2], a_middle[2]], rgbcolor="green", alpha=0.6)
median_point = point(
(
(xy[0][0]+xy[1][0]+xy[2][0])/3.0,
(xy[0][1]+xy[1][1]+xy[2][1])/3.0
), rgbcolor="green", pointsize=28)
median_graph = a_median + b_median + c_median + median_point
else:
median_graph = Graphics()
# Perpendicular Bisectors
if show_pb:
a_pb = line_to_points(a_middle[0], half(a, 1, 2, 0), rgbcolor="red", alpha=0.6)
b_pb = line_to_points(a_middle[1], half(a, 2, 0, 1), rgbcolor="red", alpha=0.6)
c_pb = line_to_points(a_middle[2], half(a, 0, 1, 2), rgbcolor="red", alpha=0.6)
pb_point = point((0, 0), rgbcolor="red", pointsize=28)
pb_graph = a_pb + b_pb + c_pb + pb_point
else:
pb_graph = Graphics()
# Altitudes
if show_alt:
xA, xB, xC = xy[0][0], xy[1][0], xy[2][0]
yA, yB, yC = xy[0][1], xy[1][1], xy[2][1]
a_alt = plot(((xC-xB)*x+(xB-xC)*xA)/(yB-yC)+yA, (x,-3,3), rgbcolor="brown", alpha=0.6)
b_alt = plot(((xA-xC)*x+(xC-xA)*xB)/(yC-yA)+yB, (x,-3,3), rgbcolor="brown", alpha=0.6)
c_alt = plot(((xB-xA)*x+(xA-xB)*xC)/(yA-yB)+yC, (x,-3,3), rgbcolor="brown", alpha=0.6)
alt_lx = (xA*xB*(yA-yB)+xB*xC*(yB-yC)+xC*xA*(yC-yA)-(yA-yB)*(yB-yC)*(yC-yA))/(xC*yB-xB*yC+xA*yC-xC*yA+xB*yA-xA*yB)
alt_ly = (yA*yB*(xA-xB)+yB*yC*(xB-xC)+yC*yA*(xC-xA)-(xA-xB)*(xB-xC)*(xC-xA))/(yC*xB-yB*xC+yA*xC-yC*xA+yB*xA-yA*xB)
alt_intersection = point((alt_lx, alt_ly), rgbcolor="brown", pointsize=28)
alt_graph = a_alt + b_alt + c_alt + alt_intersection
else:
alt_graph = Graphics()
# Euler's Line
if show_euler:
euler_graph = line_to_points(
(0, 0),
(
(xy[0][0]+xy[1][0]+xy[2][0])/3.0,
(xy[0][1]+xy[1][1]+xy[2][1])/3.0
),
rgbcolor="purple",
thickness=2,
alpha=0.7
)
else:
euler_graph = Graphics()
show(
C + triangle + triangle_points + labels + ab_graph + median_graph +
pb_graph + alt_graph + incircle_graph + euler_graph,
figsize=[5,5], xmin=-1, xmax=1, ymin=-1, ymax=1
)
@library_interact
def coin(n = slider(2,10000, 100, default=1000, label="Number of Tosses"), interval = range_slider(0, 1, default=(0.45, 0.55), label="Plotting range (y)")):
"""
This interact demo simulates repeated tosses of a coin,
based on work by Lauri Ruotsalainen, 2010.
The points give the cumulative percentage of tosses which
are heads in a given run of the simulation, so that the
point `(x,y)` gives the percentage of the first `x` tosses
that were heads; this proportion should approach .5, of
course, if we are simulating a fair coin.
INPUT:
- ``n`` -- number of tosses
- ``interval`` -- plot range along
vertical axis
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.statistics.coin()
Interactive function <function coin at ...> with 2 widgets
n: IntSlider(value=1000, description=u'Number of Tosses', max=10000, min=2, step=100)
interval: IntRangeSlider(value=(0, 0), description=u'Plotting range (y)', max=1)
"""
from random import random
c = []
k = 0.0
for i in range(1, n + 1):
k += random()
c.append((i, k/i))
show(point(c[1:], gridlines=[None, [0.5]], pointsize=1), ymin=interval[0], ymax=interval[1])
@library_interact
def bisection_method(
title = text_control('<h2>Bisection method</h2>'),
f = input_box("x^2-2", label='f(x)'),
interval = range_slider(-5,5,default=(0, 4), label="range"),
d = slider(1, 8, 1, 3, label="$10^{-d}$ precision"),
maxn = slider(0,50,1,10, label="max iterations")):
"""
Interact explaining the bisection method, based on similar interact
explaining secant method and Wiliam Stein's example from wiki.
INPUT:
- ``f`` -- function
- ``interval`` -- range slider for the search interval
- ``d`` -- slider for the precision (`10^{-d}`)
- ``maxn`` -- max number of iterations
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.calculus.secant_method()
Interactive function <function secant_method at ...> with 5 widgets
title: HTMLText(value=u'<h2>Secant method for numerical root finding</h2>')
f: EvalText(value=u'x^2-2', description=u'f(x)', layout=Layout(max_width=u'81em'))
interval: IntRangeSlider(value=(0, 4), description=u'range', max=5, min=-5)
d: IntSlider(value=3, description=u'10^-d precision', max=16, min=1)
maxn: IntSlider(value=10, description=u'max iterations', max=15)
"""
def _bisection_method(f, a, b, maxn, eps):
intervals = [(a,b)]
round = 1
two = float(2)
while True:
c = (b+a)/two
if abs(f(c)) < h or round >= maxn:
break
fa = f(a); fb = f(b); fc = f(c)
if abs(fc) < eps:
return c, intervals
if fa*fc < 0:
a, b = a, c
elif fc*fb < 0:
a, b = c, b
else:
raise ValueError("f must have a sign change in the interval (%s,%s)"%(a,b))
intervals.append((a,b))
round += 1
return c, intervals
x = SR.var('x')
f = symbolic_expression(f).function(x)
a, b = interval
h = 10**(-d)
try:
c, intervals = _bisection_method(f, float(a), float(b), maxn, h)
except ValueError:
print("f must have opposite sign at the endpoints of the interval")
show(plot(f, a, b, color='red'), xmin=a, xmax=b)
else:
html(r"$\text{Precision }h = 10^{-d}=10^{-%s}=%.5f$"%(d, float(h)))
html(r"${c = }%s$"%latex(c))
html(r"${f(c) = }%s"%latex(f(c)))
html(r"$%s \text{ iterations}"%len(intervals))
P = plot(f, a, b, color='red')
k = (P.ymax() - P.ymin())/ (1.5*len(intervals))
L = sum(line([(c,k*i), (d,k*i)]) for i, (c,d) in enumerate(intervals) )
L += sum(line([(c,k*i-k/4), (c,k*i+k/4)]) for i, (c,d) in enumerate(intervals) )
L += sum(line([(d,k*i-k/4), (d,k*i+k/4)]) for i, (c,d) in enumerate(intervals) )
show(P + L, xmin=a, xmax=b)
@library_interact
def secant_method(
title = text_control('<h2>Secant method for numerical root finding</h2>'),
f = input_box("x^2-2", label='f(x)'),
interval = range_slider(-5,5,default=(0, 4), label="range"),
d = slider(1, 16, 1, 3, label="10^-d precision"),
maxn = slider(0,15,1,10, label="max iterations")):
"""
Interact explaining the secant method, based on work by
Lauri Ruotsalainen, 2010.
Originally this is based on work by William Stein.
INPUT:
- ``f`` -- function
- ``interval`` -- range slider for the search interval
- ``d`` -- slider for the precision (10^-d)
- ``maxn`` -- max number of iterations
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.calculus.secant_method()
Interactive function <function secant_method at ...> with 5 widgets
title: HTMLText(value=u'<h2>Secant method for numerical root finding</h2>')
f: EvalText(value=u'x^2-2', description=u'f(x)', layout=Layout(max_width=u'81em'))
interval: IntRangeSlider(value=(0, 4), description=u'range', max=5, min=-5)
d: IntSlider(value=3, description=u'10^-d precision', max=16, min=1)
maxn: IntSlider(value=10, description=u'max iterations', max=15)
"""
def _secant_method(f, a, b, maxn, h):
intervals = [(a,b)]
round = 1
while True:
c = b-(b-a)*f(b)/(f(b)-f(a))
if abs(f(c)) < h or round >= maxn:
break
a, b = b, c
intervals.append((a,b))
round += 1
return c, intervals
x = SR.var('x')
f = symbolic_expression(f).function(x)
a, b = interval
h = 10**(-d)
if float(f(a)*f(b)) > 0:
print("f must have opposite sign at the endpoints of the interval")
show(plot(f, a, b, color='red'), xmin=a, xmax=b)
else:
c, intervals = _secant_method(f, float(a), float(b), maxn, h)
html(r"$\text{Precision }h = 10^{-d}=10^{-%s}=%.5f$"%(d, float(h)))
html(r"${c = }%s$"%latex(c))
html(r"${f(c) = }%s"%latex(f(c)))
html(r"$%s \text{ iterations}"%len(intervals))
P = plot(f, a, b, color='red')
k = (P.ymax() - P.ymin())/ (1.5*len(intervals))
L = sum(line([(c,k*i), (d,k*i)]) for i, (c,d) in enumerate(intervals) )
L += sum(line([(c,k*i-k/4), (c,k*i+k/4)]) for i, (c,d) in enumerate(intervals) )
L += sum(line([(d,k*i-k/4), (d,k*i+k/4)]) for i, (c,d) in enumerate(intervals) )
S = sum(line([(c,f(c)), (d,f(d)), (d-(d-c)*f(d)/(f(d)-f(c)), 0)], color="green") for (c,d) in intervals)
show(P + L + S, xmin=a, xmax=b)
@library_interact
def newton_method(
title = text_control('<h2>Newton method</h2>'),
f = input_box("x^2 - 2"),
c = slider(-10,10, default=6, label='Start ($x$)'),
d = slider(1, 16, 1, 3, label="$10^{-d}$ precision"),
maxn = slider(0, 15, 1, 10, label="max iterations"),
interval = range_slider(-10,10, default = (0,6), label="Interval"),
list_steps = checkbox(default=False, label="List steps")):
"""
Interact explaining the Newton method, based on work by
Lauri Ruotsalainen, 2010.
Originally this is based on work by William Stein.
INPUT:
- ``f`` -- function
- ``c`` -- starting position (`x`)
- ``d`` -- slider for the precision (`10^{-d}`)
- ``maxn`` -- max number of iterations
- ``interval`` -- range slider for the search interval
- ``list_steps`` -- checkbox, if true shows the steps numerically
EXAMPLES:
Invoked in the notebook, the following command will produce
the fully formatted interactive mathlet. In the command line,
it will simply return the underlying HTML and Sage code which
creates the mathlet::
sage: interacts.calculus.newton_method()
Interactive function <function newton_method at ...> with 7 widgets
title: HTMLText(value=u'<h2>Newton method</h2>')
f: EvalText(value=u'x^2 - 2', description=u'f', layout=Layout(max_width=u'81em'))
c: IntSlider(value=6, description=u'Start ($x$)', max=10, min=-10)
d: IntSlider(value=3, description=u'$10^{-d}$ precision', max=16, min=1)
maxn: IntSlider(value=10, description=u'max iterations', max=15)
interval: IntRangeSlider(value=(0, 6), description=u'Interval', max=10, min=-10)
list_steps: Checkbox(value=False, description=u'List steps')
"""
def _newton_method(f, c, maxn, h):
midpoints = [c]
round = 1
while True:
c = c-f(c)/f.derivative(x)(x=c)
midpoints.append(c)
if f(c-h)*f(c+h) < 0 or round == maxn:
break
round += 1
return c, midpoints
x = SR.var('x')
f = symbolic_expression(f).function(x)
a, b = interval
h = 10**(-d)
c, midpoints = _newton_method(f, float(c), maxn, 0.5 * h)
html(r"$\text{Precision } 2h = %s$"%latex(float(h)))
html(r"${c = }%s$"%c)
html(r"${f(c) = }%s"%latex(f(c)))
html(r"$%s \text{ iterations}"%len(midpoints))
if list_steps:
s = [["$n$", "$x_n$", "$f(x_n)$", r"$f(x_n-h)\,f(x_n+h)$"]]
for i, c in enumerate(midpoints):
s.append([i+1, c, f(c), (c-h)*f(c+h)])
pretty_print(table(s, header_row=True))
else:
P = plot(f, x, interval, color="blue")
L = sum(line([(c, 0), (c, f(c))], color="green") for c in midpoints[:-1])
for i in range(len(midpoints) - 1):
L += line([(midpoints[i], f(midpoints[i])), (midpoints[i+1], 0)], color="red")
show(P + L, xmin=interval[0], xmax=interval[1], ymin=P.ymin(), ymax=P.ymax())
@library_interact
def trapezoid_integration(
title = text_control('<h2>Trapezoid integration</h2>'),