Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
""" 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() <html>...</html>
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/ #*****************************************************************************
# It is important that this file is lazily imported for this to work
# 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. "range_slider", "selector", "slider", "text_control"):
""" 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 <html>...</html> """ def library_wrapper(): # This will display the interact, no need to return anything
""" Shorthand to pretty print HTML
EXAMPLES::
sage: from sage.interacts.library import html sage: html("<h1>Hello world</h1>") <h1>Hello world</h1> """
""" 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() <html>...</html> """ print(n + m)
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() <html>...</html> """
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() <html>...</html> """
# Plot function f.
# Color and calculate the area between f and the horizontal axis. interval[0], interval[1], interval[0], interval[1], latex(f(x)), f(x).nintegrate(x, interval[0], interval[1])[0] )
# Plot function g. Also color and calculate the area between g and the horizontal axis. 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. 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] )
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() <html>...</html> """ show(plots, xmin=x_range[0], xmax=x_range[1]) else:
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() <html>...</html> """ <a href="https://en.wikipedia.org/wiki/Difference_quotient" target="_blank">\ Wikipedia article about difference quotient</a></div>' )
""" 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() <html>...</html> """
color = "Red" sol = r"\text{solution} \in \mathbb{C}" color = "Blue" sol = -B/(2*A) else:
dis1 = "(%s)^2-4*%s*%s" % (B, A, C) else:
r"\frac{-%s\pm\sqrt{%s}}{2*%s} = " + \ r"\frac{-%s\pm\sqrt{%s}}{%s} = %s$"
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() <html>...</html> """
# Returns the distance between points (x1,y1) and (x2,y2)
# Returns an angle (in radians) when sides a and b # are adjacent and the side c is opposite to the angle
# Returns the area of a triangle when an angle alpha # and adjacent sides a and b are known
# Coordinates of the angles
# Side lengths (bc, ca, ab) corresponding to triangle vertices (a, b, c)
# The angles (a, b, c) in radians
# The area of the triangle
# Triangle
# Labels of the angles drawn in a distance from points
math.degrees(ak[0]), math.degrees(ak[1]), math.degrees(ak[2]) )
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() <html>...</html> """ the same length</div>')
# Unit Circle
# Graphics related to the graph of the function
# Sine # 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="--")
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() <html>...</html> """ # Return the intersection point of the bisector of the angle <(A[a],A[c],A[b]) and the unit circle. Angles given in radians. 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] + (A[b] - A[a]) / 2.0 else: p = A[b] + (2*pi - (A[b]-A[a])) / 2.0 return (math.cos(p), math.sin(p))
# Returns the distance between points (x1,y1) and (x2,y2)
# Returns the line (graph) going through points (x1,y1) and (x2,y2) (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
# Labels of the angles drawn in a distance from points
# Triangle
# Side lengths (bc, ca, ab) corresponding to triangle vertices (a, b, c)
# Midpoints of edges (bc, ca, ab) ((xy[1][0] + xy[2][0])/2.0, (xy[1][1] + xy[2][1])/2.0), ((xy[2][0] + xy[0][0])/2.0, (xy[2][1] + xy[0][1])/2.0), ((xy[0][0] + xy[1][0])/2.0, (xy[0][1] + xy[1][1])/2.0) ]
# Incircle (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 )
s = perimeter/2.0 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:
# Angle Bisectors 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:
# Medians 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:
# Perpendicular Bisectors 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:
# Altitudes 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:
# Euler's Line 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:
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 )
""" 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() <html>...</html> """
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() <html>...</html> """ return c, intervals else: raise ValueError("f must have a sign change in the interval (%s,%s)"%(a,b))
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:
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() <html>...</html> """
print("f must have opposite sign at the endpoints of the interval") show(plot(f, a, b, color='red'), xmin=a, xmax=b) else:
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() <html>...</html> """
s = [["$n$","$x_n$","$f(x_n)$", "$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:
title = text_control('<h2>Trapezoid integration</h2>'), f = input_box(default = "x^2-5*x + 10", label='$f(x)=$'), n = slider(1,100,1,5, label='# divisions'), interval_input = selector(['from slider','from keyboard'], label='Integration interval', buttons=True), interval_s = range_slider(-10,10,default=(0,8), label="slider: "), interval_g = input_grid(1,2,default=[[0,8]], label="keyboard: "), output_form = selector(['traditional','table','none'], label='Computations form', buttons=True) ): """ Interact explaining the trapezoid method for definite integrals, based on work by Lauri Ruotsalainen, 2010 (based on the application "Numerical integrals with various rules" by Marshall Hampton and Nick Alexander)
INPUT:
- ``f`` -- function of variable x to integrate - ``n`` -- number of divisions - ``interval_input`` -- swithes the input for interval between slider and keyboard - ``interval_s`` -- slider for interval to integrate - ``interval_g`` -- input grid for interval to integrate - ``output_form`` -- the computation is formatted in a traditional form, in a table or missing
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.trapezoid_integration() <html>...</html> """ else: interval = interval_g[0]
interval[0], interval[1], N(numeric_value, digits=7)) )
' + '.join([ "2 f(x_{%s})"%i for i in range(1,n)]), n ) h, N(xs[0], digits=5), ' + '.join([ "2 f(%.2f)" %N(i, digits=5) for i in xs[1:-1]]), N(xs[n], digits=5) ) h, N(ys[0], digits=5), ' + '.join([ "2\cdot %.2f" % N(i, digits=5) for i in ys[1:-1]]), N(ys[n], digits=5) )
<div class="math"> \begin{align*} \int_{%.2f}^{%.2f} {f(x) \, \mathrm{d}x} & \approx %s \\ & = %s \\ & = %s \\ & = %s \end{align*} </div> ''' % ( interval[0], interval[1], sum_formula_html, sum_placement_html, sum_values_html, N(approx, digits=7) )) elif output_form == 'table': s = [['$i$','$x_i$','$f(x_i)$','$m$','$m\cdot f(x_i)$']] for i in range(0,n+1): if i==0 or i==n: j = 1 else: j = 2 s.append([i, xs[i], ys[i],j,N(j*ys[i])]) pretty_print(table(s, header_row=True))
title = text_control('<h2>Simpson integration</h2>'), f = input_box(default = 'x*sin(x)+x+1', label='$f(x)=$'), n = slider(2,100,2,6, label='# divisions'), interval_input = selector(['from slider','from keyboard'], label='Integration interval', buttons=True), interval_s = range_slider(-10,10,default=(0,10), label="slider: "), interval_g = input_grid(1,2,default=[[0,10]], label="keyboard: "), output_form = selector(['traditional','table','none'], label='Computations form', buttons=True)): """ Interact explaining the simpson method for definite integrals, based on work by Lauri Ruotsalainen, 2010 (based on the application "Numerical integrals with various rules" by Marshall Hampton and Nick Alexander)
INPUT:
- ``f`` -- function of variable x to integrate - ``n`` -- number of divisions (mult. of 2) - ``interval_input`` -- swithes the input for interval between slider and keyboard - ``interval_s`` -- slider for interval to integrate - ``interval_g`` -- input grid for interval to integrate - ``output_form`` -- the computation is formatted in a traditional form, in a table or missing
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.simpson_integration() <html>...</html> """ else: interval = interval_g[0]
(interval[0],interval[1], N(numeric_value,digits=7)))
' + '.join([ r"%s \cdot f(x_{%s})" %(i%2*(-2)+4, i+1) for i in range(0,n-1)]), n )
dx, N(xs[0],digits=5), ' + '.join([ r"%s \cdot f(%.2f)" %(i%2*(-2)+4, N(xk, digits=5)) for i, xk in enumerate(xs[1:-1])]), N(xs[n],digits=5) )
dx, "%.2f + "%N(ys[0],digits=5), ' + '.join([ r"%s \cdot %.2f" %(i%2*(-2)+4, N(yk, digits=5)) for i, yk in enumerate(ys[1:-1])]), " + %.2f"%N(ys[n],digits=5) )
<div class="math"> \begin{align*} \int_{%.2f}^{%.2f} {f(x) \, \mathrm{d}x} & \approx %s \\ & = %s \\ & = %s \\ & = %.6f \end{align*} </div> ''' % ( interval[0], interval[1], sum_formula_html, sum_placement_html, sum_values_html, N(approx,digits=7) )) elif output_form == 'table': s = [['$i$','$x_i$','$f(x_i)$','$m$','$m\cdot f(x_i)$']] for i in range(0,n+1): if i==0 or i==n: j = 1 else: j = (i+1)%2*(-2)+4 s.append([i, xs[i], ys[i],j,N(j*ys[i])]) s.append(['','','','$\sum$','$%s$'%latex(3/dx*approx)]) pretty_print(table(s, header_row=True)) html(r'$\int_{%.2f}^{%.2f} {f(x) \, \mathrm{d}x}\approx\frac {%.2f}{3}\cdot %s=%s$'% (interval[0], interval[1],dx,latex(3/dx*approx),latex(approx)))
title = text_control('<h2>Riemann integral with random sampling</h2>'), f = input_box("x^2+1", label = "$f(x)=$", width=40), n = slider(1,30,1,5, label='# divisions'), hr1 = text_control('<hr>'), interval_input = selector(['from slider','from keyboard'], label='Integration interval', buttons=True), interval_s = range_slider(-5,10,default=(0,2), label="slider: "), interval_g = input_grid(1,2,default=[[0,2]], label="keyboard: "), hr2 = text_control('<hr>'), list_table = checkbox(default=False, label="List table"), auto_update = False): """ Interact explaining the definition of Riemann integral
INPUT:
- ``f`` -- function of variable x to integrate - ``n`` -- number of divisions - ``interval_input`` -- swithes the input for interval between slider and keyboard - ``interval_s`` -- slider for interval to integrate - ``interval_g`` -- input grid for interval to integrate - ``list_table`` -- print table with values of the function
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.riemann_sum() <html>...</html>
AUTHORS:
- Robert Marik (08-2010) """ else: a = interval_g[0][0] b = interval_g[0][1] else: color_rect='red' + point((xs[i],ys[i]), rgbcolor = (1,0,0))\ + line(body,rgbcolor='black',zorder=-1)
pretty_print(table([ ["$i$", "$[x_{i-1},x_i]$", "$\eta_i$", "$f(\eta_i)$", "$x_{i}-x_{i-1}$"] ] + [ [i+1,[division[i],division[i+1]],xs[i],ys[i],delka_intervalu[i]] for i in range(n) ], header_row=True))
(latex(n),latex(sum([ys[i]*delka_intervalu[i] for i in range(n)])))) (latex(a),latex(b),latex(func(x)),latex(integral_numerical(func(x),a,b)[0])))
yrange='auto', a=1, action=selector(['f', 'df/dx', 'int f', 'num f', 'den f', '1/f', 'finv', 'f+a', 'f-a', 'f*a', 'f/a', 'f^a', 'f(x+a)', 'f(x*a)', 'f+g', 'f-g', 'f*g', 'f/g', 'f(g)'], width=15, nrows=5, label="h = "), do_plot = ("Draw Plots", True)): """ `Function Plotting Tool <http://wiki.sagemath.org/interact/calculus#Functiontool>`_ (by William Stein (?))
INPUT:
- ``f`` -- function f(x) - ``g`` -- function g(x) - ``xrange`` -- range for plotting (x) - ``yrange`` -- range for plotting ('auto' is default, otherwise a tuple) - ``a`` -- factor ``a`` - ``action`` -- select given operation on or combination of functions - ``do_plot`` -- if true, a plot is drawn
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_tool() <html>...</html> """ except TypeError as msg: print(msg[-200:]) print("Unable to make sense of f,g, or a as symbolic expressions in single variable x.") return xrange = (0,1) elif action == 'df/dx': h = f.derivative(x) lbl = r'\frac{\mathrm{d}f}{\mathrm{d}x}' elif action == 'int f': h = f.integrate(x) lbl = r'\int f \,\mathrm{d}x' elif action == 'num f': h = f.numerator() lbl = r'\text{numer(f)}' elif action == 'den f': h = f.denominator() lbl = r'\text{denom(f)}' elif action == '1/f': h = 1/f lbl = r'\frac{1}{f}' elif action == 'finv': h = solve(f == var('y'), x)[0].rhs() lbl = 'f^{-1}(y)' elif action == 'f+a': h = f+a lbl = 'f + a' elif action == 'f-a': h = f-a lbl = 'f - a' elif action == 'f*a': h = f*a lbl = r'f \times a' elif action == 'f/a': h = f/a lbl = r'\frac{f}{a}' elif action == 'f^a': h = f**a lbl = 'f^a' elif action == 'f^a': h = f**a lbl = 'f^a' elif action == 'f(x+a)': h = f.subs(x=x+a) lbl = 'f(x+a)' elif action == 'f(x*a)': h = f.subs(x=x*a) lbl = 'f(xa)' elif action == 'f+g': h = f+g lbl = 'f + g' elif action == 'f-g': h = f-g lbl = 'f - g' elif action == 'f*g': h = f*g lbl = r'f \times g' elif action == 'f/g': h = f/g lbl = r'\frac{f}{g}' elif action == 'f(g)': h = f(g) lbl = 'f(g)' plot(g, xrange, color='green', thickness=2) + \ plot(h, xrange, color='blue', thickness=2) else: yrange = sage_eval(yrange) show(P, xmin=xrange[0], xmax=xrange[1], ymin=yrange[0], ymax=yrange[1])
c_real = slider(-2,2,0.01,0.5, label='real part const.'), c_imag = slider(-2,2,0.01,0.5, label='imag part const.'), iterations=slider(1,100,1,20, label='# iterations'), zoom_x = range_slider(-2,2,0.01,(-1.5,1.5), label='Zoom X'), zoom_y = range_slider(-2,2,0.01,(-1.5,1.5), label='Zoom Y'), plot_points = slider(20,400,20, default=150, label='plot points'), dpi = slider(20, 200, 10, default=80, label='dpi')): """ Julia Fractal, based on `Julia by Harald Schilly <http://wiki.sagemath.org/interact/fractal#Julia>`_.
INPUT:
- ``exponent`` -- exponent ``e`` in `z^e+c` - ``c_real`` -- real part of the constant ``c`` - ``c_imag`` -- imaginary part of the constant ``c`` - ``iterations`` -- number of iterations - ``zoom_x`` -- range slider for zoom in x direction - ``zoom_y`` -- range slider for zoom in y direction - ``plot_points`` -- number of points to plot - ``dpi`` -- dots-per-inch parameter for the plot
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.fractals.julia() <html>...</html> """
iterations=slider(1,100,1,20, label='# iterations'), zoom_x = range_slider(-2,2,0.01,(-2,1), label='Zoom X'), zoom_y = range_slider(-2,2,0.01,(-1.5,1.5), label='Zoom Y'), plot_points = slider(20,400,20, default=150, label='plot points'), dpi = slider(20, 200, 10, default=80, label='dpi')): """ Mandelbrot Fractal, based on `Mandelbrot by Harald Schilly <http://wiki.sagemath.org/interact/fractal#Mandelbrot>`_.
INPUT:
- ``exponent`` -- exponent ``e`` in `z^e+c` - ``iterations`` -- number of iterations - ``zoom_x`` -- range slider for zoom in x direction - ``zoom_y`` -- range slider for zoom in y direction - ``plot_points`` -- number of points to plot - ``dpi`` -- dots-per-inch parameter for the plot
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.fractals.mandelbrot() <html>...</html> """
N=slider(1,500,1,label='Number of iterations',default=100), rule_number=slider(0, 255, 1, default=110, label='Rule number'), size = slider(1, 11, step_size=1, default=6, label='size of graphic')): """ Yields a matrix showing the evolution of a `Wolfram's cellular automaton <http://mathworld.wolfram.com/CellularAutomaton.html>`_.
`Based on work by Pablo Angulo <http://wiki.sagemath.org/interact/misc#CellularAutomata>`_.
INPUT:
- ``N`` -- iterations - ``rule_number`` -- rule number (0 to 255) - ``size`` -- size of the shown picture
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.fractals.cellular_automaton() <html>...</html> """ raise ValueError('Invalid rule number')
'<div style="white-space: normal;">"A cellular automaton is a collection of "colored" cells \ on a grid of specified shape that evolves through a number of \ discrete time steps according to a set of rules based on the \ states of neighboring cells." — \ <a target="_blank" href="http://mathworld.wolfram.com/CellularAutomaton.html">Mathworld,\ Cellular Automaton</a></div>\ <div>Rule %s expands to %s</div>' % (rule_number, ''.join(map(str,rule))) )
interval = range_slider(1, 4000, 10, default=(1, 1000), label="range"), show_factors = True, highlight_primes = True, show_curves = True, n = slider(1,200, 1, default=89, label="number $n$"), dpi = slider(10,300, 10, default=100, label="dpi")): """ Polar Prime Spiral interact, based on work by David Runde.
For more information about the factors in the spiral, `visit John Williamson's website <http://www.dcs.gla.ac.uk/~jhw/spirals/index.html>`_.
INPUT:
- ``interval`` -- range slider to specify start and end - ``show_factors`` -- if true, show factors - ``highlight_primes`` -- if true, prime numbers are highlighted - ``show_curves`` -- if true, curves are plotted - ``n`` -- number `n` - ``dpi`` -- dots per inch resolution for plotting
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: sage.interacts.algebra.polar_prime_spiral() <html>...</html>
"""
html('<h2>Polar Prime Spiral</h2> \ <div style="white-space: normal;">\ For more information about the factors in the spiral, visit \ <a href="http://www.dcs.gla.ac.uk/~jhw/spirals/index.html" target="_blank">\ Number Spirals by John Williamson</a>.</div>' )
start, end = interval from sage.ext.fast_eval import fast_float from math import floor, ceil from sage.plot.colors import hue
if start < 1 or end <= start: print("invalid start or end value") return if n > end: print("WARNING: n is greater than end value") return if n < start: print("n < start value") return nn = SR.var('nn') f1 = fast_float(sqrt(nn)*cos(2*pi*sqrt(nn)), 'nn') f2 = fast_float(sqrt(nn)*sin(2*pi*sqrt(nn)), 'nn') f = lambda x: (f1(x), f2(x))
list = [] list2 = [] if not show_factors: for i in srange(start, end, include_endpoint = True): if Integer(i).is_pseudoprime(): list.append(f(i-start+1)) #Primes list else: list2.append(f(i-start+1)) #Composites list P = points(list) R = points(list2, alpha = .1) #Faded Composites else: for i in srange(start, end, include_endpoint = True): list.append(disk((f(i-start+1)),0.05*pow(2,len(factor(i))-1), (0,2*pi))) #resizes each of the dots depending of the number of factors of each number if Integer(i).is_pseudoprime() and highlight_primes: list2.append(f(i-start+1)) P = Graphics() for g in list: P += g p_size = 5 #the orange dot size of the prime markers if not highlight_primes: list2 = [(f(n-start+1))] R = points(list2, hue = .1, pointsize = p_size)
if n > 0: html('$n = %s$' % factor(n))
p = 1 #The X which marks the given n W1 = disk((f(n-start+1)), p, (pi/6, 2*pi/6), alpha=.1) W2 = disk((f(n-start+1)), p, (4*pi/6, 5*pi/6), alpha=.1) W3 = disk((f(n-start+1)), p, (7*pi/6, 8*pi/6), alpha=.1) W4 = disk((f(n-start+1)), p, (10*pi/6, 11*pi/6), alpha=.1) Q = W1 + W2 + W3 + W4
n = n - start +1 #offsets the n for different start values to ensure accurate plotting if show_curves: begin_curve = 0 t = SR.var('t') a=1.0 b=0.0 if n > (floor(sqrt(n)))**2 and n <= (floor(sqrt(n)))**2 + floor(sqrt(n)): c = -((floor(sqrt(n)))**2 - n) c2= -((floor(sqrt(n)))**2 + floor(sqrt(n)) - n) else: c = -((ceil(sqrt(n)))**2 - n) c2= -((floor(sqrt(n)))**2 + floor(sqrt(n)) - n) html('Pink Curve: $n^2 + %s$' % c) html('Green Curve: $n^2 + n + %s$' % c2) m = SR.var('m') g = symbolic_expression(a*m**2+b*m+c).function(m) r = symbolic_expression(sqrt(g(m))).function(m) theta = symbolic_expression(r(m)- m*sqrt(a)).function(m) S1 = parametric_plot(((r(t))*cos(2*pi*(theta(t))),(r(t))*sin(2*pi*(theta(t)))), (begin_curve, ceil(sqrt(end-start))), color=hue(0.8), thickness = .3) #Pink Line
b = 1 c = c2; g = symbolic_expression(a*m**2+b*m+c).function(m) r = symbolic_expression(sqrt(g(m))).function(m) theta = symbolic_expression(r(m)- m*sqrt(a)).function(m) S2 = parametric_plot(((r(t))*cos(2*pi*(theta(t))),(r(t))*sin(2*pi*(theta(t)))), (begin_curve, ceil(sqrt(end-start))), color=hue(0.6), thickness = .3) #Green Line
show(R+P+S1+S2+Q, aspect_ratio = 1, axes = False, dpi = dpi) else: show(R+P+Q, aspect_ratio = 1, axes = False, dpi = dpi) else: show(R+P, aspect_ratio = 1, axes = False, dpi = dpi) |