CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.

| Download

class1

Views: 20
Image: ubuntu2204
for n in range (1,100): if (n%3)*(n%5)*(n)==0: print(n)
3 5 6 7 9 10 12 14 15 18 20 21 24 25 27 28 30 33 35 36 39 40 42 45 48 49 50 51 54 55 56 57 60 63 65 66 69 70 72 75 77 78 80 81 84 85 87 90 91 93 95 96 98 99
N=10 L=[] for n in [1..N]: if n%2==0: L.append(n) print(L)
[2, 4, 6, 8, 10]
for n in [10..10000]: if n.digits()[1]==4 and (n%11)==0: print(n)
44 143 242 341 440 649 748 847 946 1045 1144 1243 1342 1441 1540 1749 1848 1947 2046 2145 2244 2343 2442 2541 2640 2849 2948 3047 3146 3245 3344 3443 3542 3641 3740 3949 4048 4147 4246 4345 4444 4543 4642 4741 4840 5049 5148 5247 5346 5445 5544 5643 5742 5841 5940 6149 6248 6347 6446 6545 6644 6743 6842 6941 7040 7249 7348 7447 7546 7645 7744 7843 7942 8041 8140 8349 8448 8547 8646 8745 8844 8943 9042 9141 9240 9449 9548 9647 9746 9845 9944
N=10000 L=[n for n in [10..N] if n%11==0 and n.digits()[1]==4] print(L)
[44, 143, 242, 341, 440, 649, 748, 847, 946, 1045, 1144, 1243, 1342, 1441, 1540, 1749, 1848, 1947, 2046, 2145, 2244, 2343, 2442, 2541, 2640, 2849, 2948, 3047, 3146, 3245, 3344, 3443, 3542, 3641, 3740, 3949, 4048, 4147, 4246, 4345, 4444, 4543, 4642, 4741, 4840, 5049, 5148, 5247, 5346, 5445, 5544, 5643, 5742, 5841, 5940, 6149, 6248, 6347, 6446, 6545, 6644, 6743, 6842, 6941, 7040, 7249, 7348, 7447, 7546, 7645, 7744, 7843, 7942, 8041, 8140, 8349, 8448, 8547, 8646, 8745, 8844, 8943, 9042, 9141, 9240, 9449, 9548, 9647, 9746, 9845, 9944]
help(divisors)
Help on function divisors in module sage.arith.misc: divisors(n) Return the list of all divisors (up to units) of this element of a unique factorization domain. For an integer, the list of all positive integer divisors of this integer, sorted in increasing order, is returned. INPUT: - ``n`` - the element EXAMPLES: Divisors of integers:: sage: divisors(-3) [1, 3] sage: divisors(6) [1, 2, 3, 6] sage: divisors(28) [1, 2, 4, 7, 14, 28] sage: divisors(2^5) [1, 2, 4, 8, 16, 32] sage: divisors(100) [1, 2, 4, 5, 10, 20, 25, 50, 100] sage: divisors(1) [1] sage: divisors(0) Traceback (most recent call last): ... ValueError: n must be nonzero sage: divisors(2^3 * 3^2 * 17) [1, 2, 3, 4, 6, 8, 9, 12, 17, 18, 24, 34, 36, 51, 68, 72, 102, 136, 153, 204, 306, 408, 612, 1224] This function works whenever one has unique factorization:: sage: K.<a> = QuadraticField(7) # optional - sage.rings.number_field sage: divisors(K.ideal(7)) # optional - sage.rings.number_field [Fractional ideal (1), Fractional ideal (a), Fractional ideal (7)] sage: divisors(K.ideal(3)) # optional - sage.rings.number_field [Fractional ideal (1), Fractional ideal (3), Fractional ideal (a - 2), Fractional ideal (a + 2)] sage: divisors(K.ideal(35)) # optional - sage.rings.number_field [Fractional ideal (1), Fractional ideal (5), Fractional ideal (a), Fractional ideal (7), Fractional ideal (5*a), Fractional ideal (35)] TESTS:: sage: divisors(int(300)) [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 25, 30, 50, 60, 75, 100, 150, 300] sage: import numpy # optional - numpy sage: divisors(numpy.int8(100)) # optional - numpy [1, 2, 4, 5, 10, 20, 25, 50, 100] sage: import gmpy2 sage: divisors(gmpy2.mpz(100)) [1, 2, 4, 5, 10, 20, 25, 50, 100] sage: divisors([]) Traceback (most recent call last): ... TypeError: unable to factor []
for n in [1..1000]: if len(divisors(n))==8: print(n)
24 30 40 42 54 56 66 70 78 88 102 104 105 110 114 128 130 135 136 138 152 154 165 170 174 182 184 186 189 190 195 222 230 231 232 238 246 248 250 255 258 266 273 282 285 286 290 296 297 310 318 322 328 344 345 351 354 357 366 370 374 375 376 385 399 402 406 410 418 424 426 429 430 434 435 438 442 455 459 465 470 472 474 483 488 494 498 506 513 518 530 534 536 555 561 568 574 582 584 590 595 598 602 606 609 610 615 618 621 627 632 638 642 645 646 651 654 658 663 664 665 670 678 682 686 705 710 712 715 730 741 742 754 759 762 776 777 782 783 786 790 795 805 806 808 814 822 824 826 830 834 837 854 856 861 872 874 875 885 890 894 897 902 903 904 906 915 935 938 942 946 957 962 969 970 978 986 987 994 999
while k<100: n=1 if n.is_prime() and k%n==0: else: n+=1
True
L1=[3^n for n in [0..5]] L2=[5^n for n in [0..5]] result=[] for k in [0..4]: for i in [0..4]: result.append(L1[k]*L2[i]) print(result.sort())
None
2+3
5
help(integral)
Help on function integral in module sage.misc.functional: integral(x, *args, **kwds) Return an indefinite or definite integral of an object ``x``. First call ``x.integral()`` and if that fails make an object and integrate it using Maxima, maple, etc, as specified by algorithm. For symbolic expression calls :func:`sage.calculus.calculus.integral` - see this function for available options. EXAMPLES:: sage: f = cyclotomic_polynomial(10) sage: integral(f) 1/5*x^5 - 1/4*x^4 + 1/3*x^3 - 1/2*x^2 + x :: sage: integral(sin(x),x) -cos(x) :: sage: y = var('y') sage: integral(sin(x),y) y*sin(x) :: sage: integral(sin(x), x, 0, pi/2) 1 sage: sin(x).integral(x, 0,pi/2) 1 sage: integral(exp(-x), (x, 1, oo)) e^(-1) Numerical approximation:: sage: h = integral(tan(x)/x, (x, 1, pi/3)) ... sage: h integrate(tan(x)/x, x, 1, 1/3*pi) sage: h.n() 0.07571599101... Specific algorithm can be used for integration:: sage: integral(sin(x)^2, x, algorithm='maxima') 1/2*x - 1/4*sin(2*x) sage: integral(sin(x)^2, x, algorithm='sympy') -1/2*cos(x)*sin(x) + 1/2*x TESTS: A symbolic integral from :trac:`11445` that was incorrect in earlier versions of Maxima:: sage: f = abs(x - 1) + abs(x + 1) - 2*abs(x) sage: integrate(f, (x, -Infinity, Infinity)) 2 Another symbolic integral, from :trac:`11238`, that used to return zero incorrectly; with Maxima 5.26.0 one gets ``1/2*sqrt(pi)*e^(1/4)``, whereas with 5.29.1, and even more so with 5.33.0, the expression is less pleasant, but still has the same value. Unfortunately, the computation takes a very long time with the default settings, so we temporarily use the Maxima setting ``domain: real``:: sage: sage.calculus.calculus.maxima('domain: real') real sage: f = exp(-x) * sinh(sqrt(x)) sage: t = integrate(f, x, 0, Infinity); t # long time 1/4*sqrt(pi)*(erf(1) - 1)*e^(1/4) - 1/4*(sqrt(pi)*(erf(1) - 1) - sqrt(pi) + 2*e^(-1) - 2)*e^(1/4) + 1/4*sqrt(pi)*e^(1/4) - 1/2*e^(1/4) + 1/2*e^(-3/4) sage: t.canonicalize_radical() # long time 1/2*sqrt(pi)*e^(1/4) sage: sage.calculus.calculus.maxima('domain: complex') complex An integral which used to return -1 before maxima 5.28. See :trac:`12842`:: sage: f = e^(-2*x)/sqrt(1-e^(-2*x)) sage: integrate(f, x, 0, infinity) 1 This integral would cause a stack overflow in earlier versions of Maxima, crashing sage. See :trac:`12377`. We don't care about the result here, just that the computation completes successfully:: sage: y = (x^2)*exp(x) / (1 + exp(x))^2 sage: _ = integrate(y, x, -1000, 1000) When SymPy cannot solve an integral it gives it back, so we must be able to convert SymPy's ``Integral`` (:trac:`14723`):: sage: x, y, z = var('x,y,z') sage: f = function('f') sage: integrate(f(x), x, algorithm='sympy') integrate(f(x), x) sage: integrate(f(x), x, 0, 1,algorithm='sympy') integrate(f(x), x, 0, 1) sage: integrate(integrate(integrate(f(x,y,z), x, algorithm='sympy'), y, algorithm='sympy'), z, algorithm='sympy') integrate(integrate(integrate(f(x, y, z), x), y), z) sage: integrate(sin(x)*tan(x)/(1-cos(x)), x, algorithm='sympy') -integrate(sin(x)*tan(x)/(cos(x) - 1), x) sage: _ = var('a,b,x') sage: integrate(sin(x)*tan(x)/(1-cos(x)), x, a, b, algorithm='sympy') -integrate(sin(x)*tan(x)/(cos(x) - 1), x, a, b) sage: import sympy sage: x, y, z = sympy.symbols('x y z') sage: f = sympy.Function('f') sage: SR(sympy.Integral(f(x,y,z), x, y, z)) integrate(integrate(integrate(f(x, y, z), x), y), z) Ensure that the following integral containing a signum term from :trac:`11590` can be integrated:: sage: x = SR.symbol('x', domain='real') sage: result = integrate(x * sgn(x^2 - 1/4), x, -1, 0) ... sage: result -1/4
integral(4*cos(4*x),x,0,pi/12,hold=False).show()
123\displaystyle \frac{1}{2} \, \sqrt{3}
(x^3*(x^4-4)^(1/2)).integral(x,2^(1/2),2).n()
6.92820323027551
((3*x^2+1)*(x^3+x-1)^(1/2)).integral(x,1,2).n()
17.3333333333333
var('x') f(x)=sin(2*x) g(x)=cos(x) plot(f,x,0,pi)+plot(g,x,0,pi,color='red')+plot(f(x),(x,pi/6,5*pi/6),fill=g(x)) solve(f(x)==g(x),x,to_poly_solve='force') integral.(abs(sin(2*x)-cos(x)),x,pi/6,5*pi/6).show()
x
[x == 1/2*pi + 2*pi*z2181, x == 1/6*pi + 2/3*pi*z2182]
Error in lines 6-6 Traceback (most recent call last): File "/cocalc/lib/python3.11/site-packages/smc_sagews/sage_server.py", line 1245, in execute compile(block + '\n', File "<string>", line 1 integral.(abs(sin(Integer(2)*x)-cos(x)),x,pi/Integer(6),Integer(5)*pi/Integer(6)).show() ^ SyntaxError: invalid syntax
help(plot)
Help on function plot in module sage.plot.plot: plot(funcs, *args, **kwds) Use plot by writing ``plot(X, ...)`` where `X` is a Sage object (or list of Sage objects) that either is callable and returns numbers that can be coerced to floats, or has a plot method that returns a ``GraphicPrimitive`` object. There are many other specialized 2D plot commands available in Sage, such as ``plot_slope_field``, as well as various graphics primitives like :class:`~sage.plot.arrow.Arrow`; type ``sage.plot.plot?`` for a current list. Type ``plot.options`` for a dictionary of the default options for plots. You can change this to change the defaults for all future plots. Use ``plot.reset()`` to reset to the default options. PLOT OPTIONS: - ``plot_points`` -- (default: `200`); the minimal number of plot points. - ``adaptive_recursion`` -- (default: `5`); how many levels of recursion to go before giving up when doing adaptive refinement. Setting this to 0 disables adaptive refinement. - ``adaptive_tolerance`` -- (default: `0.01`); how large a difference should be before the adaptive refinement code considers it significant. See the documentation further below for more information, starting at "the algorithm used to insert". - ``imaginary_tolerance`` -- (default: ``1e-8``); if an imaginary number arises (due, for example, to numerical issues), this tolerance specifies how large it has to be in magnitude before we raise an error. In other words, imaginary parts smaller than this are ignored in your plot points. - ``base`` -- (default: `10`); the base of the logarithm if a logarithmic scale is set. This must be greater than 1. The base can be also given as a list or tuple ``(basex, basey)``. ``basex`` sets the base of the logarithm along the horizontal axis and ``basey`` sets the base along the vertical axis. - ``scale`` -- string (default: ``"linear"``); scale of the axes. Possible values are ``"linear"``, ``"loglog"``, ``"semilogx"``, ``"semilogy"``. The scale can be also be given as single argument that is a list or tuple ``(scale, base)`` or ``(scale, basex, basey)``. The ``"loglog"`` scale sets both the horizontal and vertical axes to logarithmic scale. The ``"semilogx"`` scale sets the horizontal axis to logarithmic scale. The ``"semilogy"`` scale sets the vertical axis to logarithmic scale. The ``"linear"`` scale is the default value when :class:`~sage.plot.graphics.Graphics` is initialized. - ``xmin`` -- starting x value in the rendered figure. This parameter is passed directly to the ``show`` procedure and it could be overwritten. - ``xmax`` -- ending x value in the rendered figure. This parameter is passed directly to the ``show`` procedure and it could be overwritten. - ``ymin`` -- starting y value in the rendered figure. This parameter is passed directly to the ``show`` procedure and it could be overwritten. - ``ymax`` -- ending y value in the rendered figure. This parameter is passed directly to the ``show`` procedure and it could be overwritten. - ``detect_poles`` -- (default: ``False``) If set to ``True`` poles are detected. If set to "show" vertical asymptotes are drawn. - ``legend_label`` -- a (TeX) string serving as the label for `X` in the legend. If `X` is a list, then this option can be a single string, or a list or dictionary with strings as entries/values. If a dictionary, then keys are taken from ``range(len(X))``. .. NOTE:: - If the ``scale`` is ``"linear"``, then irrespective of what ``base`` is set to, it will default to 10 and will remain unused. - If you want to limit the plot along the horizontal axis in the final rendered figure, then pass the ``xmin`` and ``xmax`` keywords to the :meth:`~sage.plot.graphics.Graphics.show` method. To limit the plot along the vertical axis, ``ymin`` and ``ymax`` keywords can be provided to either this ``plot`` command or to the ``show`` command. - This function does NOT simply sample equally spaced points between xmin and xmax. Instead it computes equally spaced points and adds small perturbations to them. This reduces the possibility of, e.g., sampling `\sin` only at multiples of `2\pi`, which would yield a very misleading graph. - If there is a range of consecutive points where the function has no value, then those points will be excluded from the plot. See the example below on automatic exclusion of points. - For the other keyword options that the ``plot`` function can take, refer to the method :meth:`~sage.plot.graphics.Graphics.show` and the further options below. COLOR OPTIONS: - ``color`` - (Default: 'blue') One of: - an RGB tuple (r,g,b) with each of r,g,b between 0 and 1. - a color name as a string (e.g., 'purple'). - an HTML color such as '#aaff0b'. - a list or dictionary of colors (valid only if `X` is a list): if a dictionary, keys are taken from ``range(len(X))``; the entries/values of the list/dictionary may be any of the options above. - 'automatic' -- maps to default ('blue') if `X` is a single Sage object; and maps to a fixed sequence of regularly spaced colors if `X` is a list. - ``legend_color`` - the color of the text for `X` (or each item in `X`) in the legend. Default color is 'black'. Options are as in ``color`` above, except that the choice 'automatic' maps to 'black' if `X` is a single Sage object. - ``fillcolor`` - The color of the fill for the plot of `X` (or each item in `X`). Default color is 'gray' if `X` is a single Sage object or if ``color`` is a single color. Otherwise, options are as in ``color`` above. APPEARANCE OPTIONS: The following options affect the appearance of the line through the points on the graph of `X` (these are the same as for the line function): INPUT: - ``alpha`` -- how transparent the line is - ``thickness`` -- how thick the line is - ``rgbcolor`` -- the color as an RGB tuple - ``hue`` -- the color given as a hue LINE OPTIONS: Any MATPLOTLIB line option may also be passed in. E.g., - ``linestyle`` - (default: "-") The style of the line, which is one of - ``"-"`` or ``"solid"`` - ``"--"`` or ``"dashed"`` - ``"-."`` or ``"dash dot"`` - ``":"`` or ``"dotted"`` - ``"None"`` or ``" "`` or ``""`` (nothing) - a list or dictionary (see below) The linestyle can also be prefixed with a drawing style (e.g., ``"steps--"``) - ``"default"`` (connect the points with straight lines) - ``"steps"`` or ``"steps-pre"`` (step function; horizontal line is to the left of point) - ``"steps-mid"`` (step function; points are in the middle of horizontal lines) - ``"steps-post"`` (step function; horizontal line is to the right of point) If `X` is a list, then ``linestyle`` may be a list (with entries taken from the strings above) or a dictionary (with keys in ``range(len(X))`` and values taken from the strings above). - ``marker`` - The style of the markers, which is one of - ``"None"`` or ``" "`` or ``""`` (nothing) -- default - ``","`` (pixel), ``"."`` (point) - ``"_"`` (horizontal line), ``"|"`` (vertical line) - ``"o"`` (circle), ``"p"`` (pentagon), ``"s"`` (square), ``"x"`` (x), ``"+"`` (plus), ``"*"`` (star) - ``"D"`` (diamond), ``"d"`` (thin diamond) - ``"H"`` (hexagon), ``"h"`` (alternative hexagon) - ``"<"`` (triangle left), ``">"`` (triangle right), ``"^"`` (triangle up), ``"v"`` (triangle down) - ``"1"`` (tri down), ``"2"`` (tri up), ``"3"`` (tri left), ``"4"`` (tri right) - ``0`` (tick left), ``1`` (tick right), ``2`` (tick up), ``3`` (tick down) - ``4`` (caret left), ``5`` (caret right), ``6`` (caret up), ``7`` (caret down), ``8`` (octagon) - ``"$...$"`` (math TeX string) - ``(numsides, style, angle)`` to create a custom, regular symbol - ``numsides`` -- the number of sides - ``style`` -- ``0`` (regular polygon), ``1`` (star shape), ``2`` (asterisk), ``3`` (circle) - ``angle`` -- the angular rotation in degrees - ``markersize`` - the size of the marker in points - ``markeredgecolor`` -- the color of the marker edge - ``markerfacecolor`` -- the color of the marker face - ``markeredgewidth`` - the size of the marker edge in points - ``exclude`` - (Default: None) values which are excluded from the plot range. Either a list of real numbers, or an equation in one variable. FILLING OPTIONS: - ``fill`` - (default: ``False``) One of: - "axis" or ``True``: Fill the area between the function and the x-axis. - "min": Fill the area between the function and its minimal value. - "max": Fill the area between the function and its maximal value. - a number c: Fill the area between the function and the horizontal line y = c. - a function g: Fill the area between the function that is plotted and g. - a dictionary ``d`` (only if a list of functions are plotted): The keys of the dictionary should be integers. The value of ``d[i]`` specifies the fill options for the i-th function in the list. If ``d[i] == [j]``: Fill the area between the i-th and the j-th function in the list. (But if ``d[i] == j``: Fill the area between the i-th function in the list and the horizontal line y = j.) - ``fillalpha`` - (default: `0.5`) How transparent the fill is. A number between 0 and 1. MATPLOTLIB STYLE SHEET OPTION: - ``stylesheet`` - (Default: classic) Support for loading a full matplotlib style sheet. Any style sheet listed in ``matplotlib.pyplot.style.available`` is acceptable. If a non-existing style is provided the default classic is applied. EXAMPLES: We plot the `\sin` function:: sage: P = plot(sin, (0,10)); print(P) Graphics object consisting of 1 graphics primitive sage: len(P) # number of graphics primitives 1 sage: len(P[0]) # how many points were computed (random) 225 sage: P # render Graphics object consisting of 1 graphics primitive .. PLOT:: P = plot(sin, (0,10)) sphinx_plot(P) :: sage: P = plot(sin, (0,10), plot_points=10); print(P) Graphics object consisting of 1 graphics primitive sage: len(P[0]) # random output 32 sage: P # render Graphics object consisting of 1 graphics primitive .. PLOT:: P = plot(sin, (0,10), plot_points=10) sphinx_plot(P) We plot with ``randomize=False``, which makes the initial sample points evenly spaced (hence always the same). Adaptive plotting might insert other points, however, unless ``adaptive_recursion=0``. :: sage: p = plot(1, (x,0,3), plot_points=4, randomize=False, adaptive_recursion=0) sage: list(p[0]) [(0.0, 1.0), (1.0, 1.0), (2.0, 1.0), (3.0, 1.0)] Some colored functions:: sage: plot(sin, 0, 10, color='purple') Graphics object consisting of 1 graphics primitive .. PLOT:: P=plot(sin,0,10,color='purple') sphinx_plot(P) :: sage: plot(sin, 0, 10, color='#ff00ff') Graphics object consisting of 1 graphics primitive .. PLOT:: P=plot(sin, 0, 10, color='#ff00ff') sphinx_plot(P) We plot several functions together by passing a list of functions as input:: sage: plot([x*exp(-n*x^2)/.4 for n in [1..5]], (0, 2), aspect_ratio=.8) Graphics object consisting of 5 graphics primitives .. PLOT:: g = plot([x*exp(-n*x**2)/.4 for n in range(1,6)], (0, 2), aspect_ratio=.8) sphinx_plot(g) By default, color will change from one primitive to the next. This may be controlled by modifying ``color`` option:: sage: g1 = plot([x*exp(-n*x^2)/.4 for n in [1..3]], (0, 2), ....: color='blue', aspect_ratio=.8); g1 Graphics object consisting of 3 graphics primitives sage: g2 = plot([x*exp(-n*x^2)/.4 for n in [1..3]], (0, 2), ....: color=['red','red','green'], linestyle=['-','--','-.'], ....: aspect_ratio=.8); g2 Graphics object consisting of 3 graphics primitives .. PLOT:: g1 = plot([x*exp(-n*x**2)/.4 for n in range(1,4)], (0, 2), color='blue', aspect_ratio=.8) g2 = plot([x*exp(-n*x**2)/.4 for n in range(1,4)], (0, 2), color=['red','red','green'], linestyle=['-','--','-.'], aspect_ratio=.8) sphinx_plot(graphics_array([[g1], [g2]])) While plotting real functions, imaginary numbers that are "almost real" will inevitably arise due to numerical issues. By tweaking the ``imaginary_tolerance``, you can decide how large of an imaginary part you're willing to sweep under the rug in order to plot the corresponding point. If a particular value's imaginary part has magnitude larger than ``imaginary_tolerance``, that point will not be plotted. The default tolerance is ``1e-8``, so the imaginary part in the first example below is ignored, but the second example "fails," emits a warning, and produces an empty graph:: sage: f = x + I*1e-12 sage: plot(f, x, -1, 1) Graphics object consisting of 1 graphics primitive sage: plot(f, x, -1, 1, imaginary_tolerance=0) ...WARNING: ...Unable to compute ... Graphics object consisting of 0 graphics primitives We can also build a plot step by step from an empty plot:: sage: a = plot([]); a # passing an empty list returns an empty plot (Graphics() object) Graphics object consisting of 0 graphics primitives sage: a += plot(x**2); a # append another plot Graphics object consisting of 1 graphics primitive .. PLOT:: a = plot([]) a = a + plot(x**2) sphinx_plot(a) :: sage: a += plot(x**3); a # append yet another plot Graphics object consisting of 2 graphics primitives .. PLOT:: a = plot([]) a = a + plot(x**2) a = a + plot(x**3) sphinx_plot(a) The function `\sin(1/x)` wiggles wildly near `0`. Sage adapts to this and plots extra points near the origin. :: sage: plot(sin(1/x), (x, -1, 1)) Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin(1/x), (x, -1, 1)) sphinx_plot(g) Via the matplotlib library, Sage makes it easy to tell whether a graph is on both sides of both axes, as the axes only cross if the origin is actually part of the viewing area:: sage: plot(x^3, (x,0,2)) # this one has the origin Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(x**3,(x,0,2)) sphinx_plot(g) :: sage: plot(x^3, (x,1,2)) # this one does not Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(x**3,(x,1,2)) sphinx_plot(g) Another thing to be aware of with axis labeling is that when the labels have quite different orders of magnitude or are very large, scientific notation (the `e` notation for powers of ten) is used:: sage: plot(x^2, (x,480,500)) # this one has no scientific notation Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(x**2,(x,480,500)) sphinx_plot(g) :: sage: plot(x^2, (x,300,500)) # this one has scientific notation on y-axis Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(x**2,(x,300,500)) sphinx_plot(g) You can put a legend with ``legend_label`` (the legend is only put once in the case of multiple functions):: sage: plot(exp(x), 0, 2, legend_label='$e^x$') Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(exp(x), 0, 2, legend_label='$e^x$') sphinx_plot(g) Sage understands TeX, so these all are slightly different, and you can choose one based on your needs:: sage: plot(sin, legend_label='sin') Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin,legend_label='sin') sphinx_plot(g) :: sage: plot(sin, legend_label='$sin$') Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin,legend_label='$sin$') sphinx_plot(g) :: sage: plot(sin, legend_label=r'$\sin$') Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin,legend_label=r'$\sin$') sphinx_plot(g) It is possible to use a different color for the text of each label:: sage: p1 = plot(sin, legend_label='sin', legend_color='red') sage: p2 = plot(cos, legend_label='cos', legend_color='green') sage: p1 + p2 Graphics object consisting of 2 graphics primitives .. PLOT:: p1 = plot(sin, legend_label='sin', legend_color='red') p2 = plot(cos, legend_label='cos', legend_color='green') g = p1 + p2 sphinx_plot(g) Prior to :trac:`19485`, legends by default had a shadowless gray background. This behavior can be recovered by setting the legend options on your plot object:: sage: p = plot(sin(x), legend_label=r'$\sin(x)$') sage: p.set_legend_options(back_color=(0.9,0.9,0.9), shadow=False) .. PLOT:: g = plot(sin(x), legend_label=r'$\sin(x)$') g.set_legend_options(back_color=(0.9,0.9,0.9), shadow=False) sphinx_plot(g) If `X` is a list of Sage objects and ``legend_label`` is 'automatic', then Sage will create labels for each function according to their internal representation:: sage: plot([sin(x), tan(x), 1 - x^2], legend_label='automatic') Graphics object consisting of 3 graphics primitives .. PLOT:: g = plot([sin(x), tan(x), 1-x**2], legend_label='automatic') sphinx_plot(g) If ``legend_label`` is any single string other than 'automatic', then it is repeated for all members of `X`:: sage: plot([sin(x), tan(x)], color='blue', legend_label='trig') Graphics object consisting of 2 graphics primitives .. PLOT:: g = plot([sin(x), tan(x)], color='blue', legend_label='trig') sphinx_plot(g) Note that the independent variable may be omitted if there is no ambiguity:: sage: plot(sin(1.0/x), (-1, 1)) Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin(1.0/x), (-1, 1)) sphinx_plot(g) Plotting in logarithmic scale is possible for 2D plots. There are two different syntaxes supported:: sage: plot(exp, (1, 10), scale='semilogy') # log axis on vertical Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(exp, (1, 10), scale='semilogy') sphinx_plot(g) :: sage: plot_semilogy(exp, (1, 10)) # same thing Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot_semilogy(exp, (1, 10)) sphinx_plot(g) :: sage: plot_loglog(exp, (1, 10)) # both axes are log Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot_loglog(exp, (1, 10)) sphinx_plot(g) :: sage: plot(exp, (1, 10), scale='loglog', base=2) # base of log is 2 # long time Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(exp, (1, 10), scale='loglog', base=2) sphinx_plot(g) We can also change the scale of the axes in the graphics just before displaying:: sage: G = plot(exp, 1, 10) # long time sage: G.show(scale=('semilogy', 2)) # long time The algorithm used to insert extra points is actually pretty simple. On the picture drawn by the lines below:: sage: p = plot(x^2, (-0.5, 1.4)) + line([(0,0), (1,1)], color='green') sage: p += line([(0.5, 0.5), (0.5, 0.5^2)], color='purple') sage: p += point(((0, 0), (0.5, 0.5), (0.5, 0.5^2), (1, 1)), ....: color='red', pointsize=20) sage: p += text('A', (-0.05, 0.1), color='red') sage: p += text('B', (1.01, 1.1), color='red') sage: p += text('C', (0.48, 0.57), color='red') sage: p += text('D', (0.53, 0.18), color='red') sage: p.show(axes=False, xmin=-0.5, xmax=1.4, ymin=0, ymax=2) .. PLOT:: g = plot(x**2, (-0.5, 1.4)) + line([(0,0), (1,1)], color='green') g = g + line([(0.5, 0.5), (0.5, 0.5**2)], color='purple') g = g + point(((0, 0), (0.5, 0.5), (0.5, 0.5**2), (1, 1)), color='red', pointsize=20) g = g + text('A', (-0.05, 0.1), color='red') g = g + text('B', (1.01, 1.1), color='red') g = g + text('C', (0.48, 0.57), color='red') g = g + text('D', (0.53, 0.18), color='red') g.axes(False) g.xmin(-0.5) g.xmax(1.4) g.ymin(0) g.ymax(2) sphinx_plot(g) You have the function (in blue) and its approximation (in green) passing through the points A and B. The algorithm finds the midpoint C of AB and computes the distance between C and D. If that distance exceeds the ``adaptive_tolerance`` threshold (*relative* to the size of the initial plot subintervals), the point D is added to the curve. If D is added to the curve, then the algorithm is applied recursively to the points A and D, and D and B. It is repeated ``adaptive_recursion`` times (5, by default). The actual sample points are slightly randomized, so the above plots may look slightly different each time you draw them. We draw the graph of an elliptic curve as the union of graphs of 2 functions. :: sage: def h1(x): return abs(sqrt(x^3 - 1)) sage: def h2(x): return -abs(sqrt(x^3 - 1)) sage: P = plot([h1, h2], 1,4) sage: P # show the result Graphics object consisting of 2 graphics primitives .. PLOT:: def h1(x): return abs(sqrt(x**3 - 1)) def h2(x): return -abs(sqrt(x**3 - 1)) P = plot([h1, h2], 1,4) sphinx_plot(P) It is important to mention that when we draw several graphs at the same time, parameters ``xmin``, ``xmax``, ``ymin`` and ``ymax`` are just passed directly to the ``show`` procedure. In fact, these parameters would be overwritten:: sage: p=plot(x^3, x, xmin=-1, xmax=1,ymin=-1, ymax=1) sage: q=plot(exp(x), x, xmin=-2, xmax=2, ymin=0, ymax=4) sage: (p+q).show() As a workaround, we can perform the trick:: sage: p1 = line([(a,b) for a, b in zip(p[0].xdata, p[0].ydata) ....: if b>=-1 and b<=1]) sage: q1 = line([(a,b) for a, b in zip(q[0].xdata, q[0].ydata) ....: if b>=0 and b<=4]) sage: (p1 + q1).show() We can also directly plot the elliptic curve:: sage: E = EllipticCurve([0,-1]) # needs sage.schemes sage: plot(E, (1, 4), color=hue(0.6)) # needs sage.schemes Graphics object consisting of 1 graphics primitive .. PLOT:: E = EllipticCurve([0,-1]) g = plot(E, (1, 4), color=hue(0.6)) sphinx_plot(g) We can change the line style as well:: sage: plot(sin(x), (x, 0, 10), linestyle='-.') Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin(x), (x, 0, 10), linestyle='-.') sphinx_plot(g) If we have an empty linestyle and specify a marker, we can see the points that are actually being plotted:: sage: plot(sin(x), (x,0,10), plot_points=20, linestyle='', marker='.') Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin(x), (x, 0, 10), plot_points=20, linestyle='', marker='.') sphinx_plot(g) The marker can be a TeX symbol as well:: sage: plot(sin(x), (x, 0, 10), plot_points=20, linestyle='', marker=r'$\checkmark$') Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin(x), (x, 0, 10), plot_points=20, linestyle='', marker=r'$\checkmark$') sphinx_plot(g) Sage currently ignores points that cannot be evaluated :: sage: from sage.misc.verbose import set_verbose sage: set_verbose(-1) sage: plot(-x*log(x), (x, 0, 1)) # this works fine since the failed endpoint is just skipped. Graphics object consisting of 1 graphics primitive sage: set_verbose(0) This prints out a warning and plots where it can (we turn off the warning by setting the verbose mode temporarily to -1.) :: sage: set_verbose(-1) sage: plot(x^(1/3), (x, -1, 1)) Graphics object consisting of 1 graphics primitive sage: set_verbose(0) .. PLOT:: set_verbose(-1) g = plot(x**(1.0/3.0), (x, -1, 1)) sphinx_plot(g) set_verbose(0) Plotting the real cube root function for negative input requires avoiding the complex numbers one would usually get. The easiest way is to use :class:`real_nth_root(x, n)<sage.functions.other.Function_real_nth_root>` :: sage: plot(real_nth_root(x, 3), (x, -1, 1)) Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(real_nth_root(x, 3), (x, -1, 1)) sphinx_plot(g) We can also get the same plot in the following way:: sage: plot(sign(x)*abs(x)^(1/3), (x, -1, 1)) Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sign(x)*abs(x)**(1./3.), (x, -1, 1)) sphinx_plot(g) A way to plot other functions without symbolic variants is to use lambda functions:: sage: plot(lambda x : RR(x).nth_root(3), (x,-1, 1)) Graphics object consisting of 1 graphics primitive .. PLOT:: sphinx_plot(plot(lambda x : RR(x).nth_root(3), (x,-1, 1))) We can detect the poles of a function:: sage: plot(gamma, (-3, 4), detect_poles=True).show(ymin=-5, ymax=5) .. PLOT:: g = plot(gamma, (-3, 4), detect_poles=True) g.ymin(-5) g.ymax(5) sphinx_plot(g) We draw the Gamma-Function with its poles highlighted:: sage: plot(gamma, (-3, 4), detect_poles='show').show(ymin=-5, ymax=5) .. PLOT:: g = plot(gamma, (-3, 4), detect_poles='show') g.ymin(-5) g.ymax(5) sphinx_plot(g) The basic options for filling a plot:: sage: p1 = plot(sin(x), -pi, pi, fill='axis') sage: p2 = plot(sin(x), -pi, pi, fill='min', fillalpha=1) sage: p3 = plot(sin(x), -pi, pi, fill='max') sage: p4 = plot(sin(x), -pi, pi, fill=(1-x)/3, ....: fillcolor='blue', fillalpha=.2) sage: graphics_array([[p1, p2], # long time ....: [p3, p4]]).show(frame=True, axes=False) .. PLOT:: p1 = plot(sin(x), -pi, pi, fill='axis'); print(p1) p2 = plot(sin(x), -pi, pi, fill='min', fillalpha=1) p3 = plot(sin(x), -pi, pi, fill='max') p4 = plot(sin(x), -pi, pi, fill=(1-x)/3, fillcolor='blue', fillalpha=.2) g = graphics_array([[p1, p2], [p3, p4]]) sphinx_plot(g, frame=True, axes=False) The basic options for filling a list of plots:: sage: (f1, f2) = x*exp(-1*x^2)/.35, x*exp(-2*x^2)/.35 sage: p1 = plot([f1, f2], -pi, pi, fill={1: [0]}, ....: fillcolor='blue', fillalpha=.25, color='blue') sage: p2 = plot([f1, f2], -pi, pi, fill={0: x/3, 1:[0]}, color=['blue']) sage: p3 = plot([f1, f2], -pi, pi, fill=[0, [0]], ....: fillcolor=['orange','red'], fillalpha=1, color={1: 'blue'}) sage: p4 = plot([f1, f2], (x,-pi, pi), fill=[x/3, 0], ....: fillcolor=['grey'], color=['red', 'blue']) sage: graphics_array([[p1, p2], # long time ....: [p3, p4]]).show(frame=True, axes=False) .. PLOT:: (f1, f2) = x*exp(-1*x**2)/.35, x*exp(-2*x**2)/.35 p1 = plot([f1, f2], -pi, pi, fill={1: [0]}, fillcolor='blue', fillalpha=.25, color='blue') p2 = plot([f1, f2], -pi, pi, fill={0: x/3, 1:[0]}, color=['blue']) p3 = plot([f1, f2], -pi, pi, fill=[0, [0]], fillcolor=['orange','red'], fillalpha=1, color={1: 'blue'}) p4 = plot([f1, f2], (x,-pi, pi), fill=[x/3, 0], fillcolor=['grey'], color=['red', 'blue']) g = graphics_array([[p1, p2], [p3, p4]]) sphinx_plot(g, frame=True, axes=False) A example about the growth of prime numbers:: sage: plot(1.13*log(x), 1, 100, ....: fill=lambda x: nth_prime(x)/floor(x), fillcolor='red') Graphics object consisting of 2 graphics primitives .. PLOT:: sphinx_plot(plot(1.13*log(x), 1, 100, fill=lambda x: nth_prime(x)/floor(x), fillcolor='red')) Fill the area between a function and its asymptote:: sage: f = (2*x^3+2*x-1)/((x-2)*(x+1)) sage: plot([f, 2*x+2], -7, 7, fill={0: [1]}, fillcolor='#ccc').show(ymin=-20, ymax=20) .. PLOT:: f = (2*x**3+2*x-1)/((x-2)*(x+1)) g = plot([f, 2*x+2], -7,7, fill={0: [1]}, fillcolor='#ccc') g.ymin(-20) g.ymax(20) sphinx_plot(g) Fill the area between a list of functions and the x-axis:: sage: def b(n): return lambda x: bessel_J(n, x) sage: plot([b(n) for n in [1..5]], 0, 20, fill='axis') Graphics object consisting of 10 graphics primitives .. PLOT:: def b(n): return lambda x: bessel_J(n, x) g = plot([b(n) for n in range(1,6)], 0, 20, fill='axis') sphinx_plot(g) Note that to fill between the ith and jth functions, you must use the dictionary key-value syntax ``i:[j]``; using key-value pairs like ``i:j`` will fill between the ith function and the line y=j:: sage: def b(n): return lambda x: bessel_J(n, x) + 0.5*(n-1) sage: plot([b(c) for c in [1..5]], 0, 20, fill={i: [i-1] for i in [1..4]}, ....: color={i: 'blue' for i in [1..5]}, aspect_ratio=3, ymax=3) Graphics object consisting of 9 graphics primitives sage: plot([b(c) for c in [1..5]], 0, 20, fill={i: i-1 for i in [1..4]}, # long time ....: color='blue', aspect_ratio=3) Graphics object consisting of 9 graphics primitives .. PLOT:: def b(n): return lambda x: bessel_J(n, x) + 0.5*(n-1) g1 = plot([b(n) for n in range(1,6)], 0, 20, fill={i:[i-1] for i in range(1,5)}, color={i:'blue' for i in range(1,6)}, aspect_ratio=3) g2 = plot([b(n) for n in range(1,6)], 0, 20, fill={i:i-1 for i in range(1,5)}, color='blue', aspect_ratio=3) g1.ymax(3) g = graphics_array([[g1], [g2]]) sphinx_plot(g) Extra options will get passed on to :meth:`~sage.plot.graphics.Graphics.show`, as long as they are valid:: sage: plot(sin(x^2), (x, -3, 3), # These labels will be nicely typeset ....: title=r'Plot of $\sin(x^2)$', axes_labels=['$x$','$y$']) Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin(x**2), (x, -3, 3), title=r'Plot of $\sin(x^2)$', axes_labels=['$x$','$y$']) sphinx_plot(g) :: sage: plot(sin(x^2), (x, -3, 3), # These will not ....: title='Plot of sin(x^2)', axes_labels=['x','y']) Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin(x**2), (x, -3, 3), title='Plot of sin(x^2)', axes_labels=['x','y']) sphinx_plot(g) :: sage: plot(sin(x^2), (x, -3, 3), # Large axes labels (w.r.t. the tick marks) ....: axes_labels=['x','y'], axes_labels_size=2.5) Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin(x**2), (x, -3, 3), axes_labels=['x','y'], axes_labels_size=2.5) sphinx_plot(g) :: sage: plot(sin(x^2), (x, -3, 3), figsize=[8,2]) Graphics object consisting of 1 graphics primitive sage: plot(sin(x^2), (x, -3, 3)).show(figsize=[8,2]) # These are equivalent .. PLOT:: g = plot(sin(x**2), (x, -3, 3), figsize=[8,2]) sphinx_plot(g) This includes options for custom ticks and formatting. See documentation for :meth:`show` for more details. :: sage: plot(sin(pi*x), (x, -8, 8), ticks=[[-7,-3,0,3,7], [-1/2,0,1/2]]) Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin(pi*x), (x, -8, 8), ticks=[[-7,-3,0,3,7],[-1/2,0,1/2]]) sphinx_plot(g) :: sage: plot(2*x + 1, (x, 0, 5), ....: ticks=[[0, 1, e, pi, sqrt(20)], ....: [1, 3, 2*e + 1, 2*pi + 1, 2*sqrt(20) + 1]], ....: tick_formatter="latex") Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(2*x + 1, (x, 0, 5), ticks=[[0, 1, e, pi, sqrt(20)], [1, 3, 2*e + 1, 2*pi + 1, 2*sqrt(20) + 1]], tick_formatter="latex") sphinx_plot(g) This is particularly useful when setting custom ticks in multiples of `\pi`. :: sage: plot(sin(x), (x,0,2*pi), ticks=pi/3, tick_formatter=pi) Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(sin(x),(x,0,2*pi),ticks=pi/3,tick_formatter=pi) sphinx_plot(g) You can even have custom tick labels along with custom positioning. :: sage: plot(x**2, (x,0,3), ticks=[[1,2.5], [0.5,1,2]], ....: tick_formatter=[["$x_1$","$x_2$"],["$y_1$","$y_2$","$y_3$"]]) Graphics object consisting of 1 graphics primitive .. PLOT:: g = plot(x**2, (x,0,3), ticks=[[1,2.5],[0.5,1,2]], tick_formatter=[["$x_1$","$x_2$"],["$y_1$","$y_2$","$y_3$"]]) sphinx_plot(g) You can force Type 1 fonts in your figures by providing the relevant option as shown below. This also requires that LaTeX, dvipng and Ghostscript be installed:: sage: plot(x, typeset='type1') # optional - latex Graphics object consisting of 1 graphics primitive A example with excluded values:: sage: plot(floor(x), (x, 1, 10), exclude=[1..10]) Graphics object consisting of 11 graphics primitives .. PLOT:: g = plot(floor(x), (x, 1, 10), exclude=list(range(1,11))) sphinx_plot(g) We exclude all points where :class:`~sage.functions.prime_pi.PrimePi` makes a jump:: sage: jumps = [n for n in [1..100] if prime_pi(n) != prime_pi(n-1)] sage: plot(lambda x: prime_pi(x), (x, 1, 100), exclude=jumps) Graphics object consisting of 26 graphics primitives .. PLOT:: #jumps = [n for n in [1..100] if prime_pi(n) != prime_pi(n-1)] #syntaxError: invalid syntax, so we need more code jumps=list() for n in range(1,101): if prime_pi(n) != prime_pi(n-1): jumps.append(n) g = plot(lambda x: prime_pi(x), (x, 1, 100), exclude=jumps) sphinx_plot(g) Excluded points can also be given by an equation:: sage: g(x) = x^2 - 2*x - 2 sage: plot(1/g(x), (x, -3, 4), exclude=g(x)==0, ymin=-5, ymax=5) # long time Graphics object consisting of 3 graphics primitives .. PLOT:: def g(x): return x**2-2*x-2 G = plot(1/g(x), (x, -3, 4), exclude=g(x)==0, ymin=-5, ymax=5) sphinx_plot(G) ``exclude`` and ``detect_poles`` can be used together:: sage: f(x) = (floor(x)+0.5) / (1-(x-0.5)^2) sage: plot(f, (x, -3.5, 3.5), detect_poles='show', exclude=[-3..3], ....: ymin=-5, ymax=5) Graphics object consisting of 12 graphics primitives .. PLOT:: def f(x): return (floor(x)+0.5) / (1-(x-0.5)**2) g = plot(f, (x, -3.5, 3.5), detect_poles='show', exclude=list(range(-3,4)), ymin=-5, ymax=5) sphinx_plot(g) Regions in which the plot has no values are automatically excluded. The regions thus excluded are in addition to the exclusion points present in the ``exclude`` keyword argument.:: sage: set_verbose(-1) sage: plot(arcsec, (x, -2, 2)) # [-1, 1] is excluded automatically Graphics object consisting of 2 graphics primitives .. PLOT:: set_verbose(-1) g = plot(arcsec, (x, -2, 2)) sphinx_plot(g) :: sage: plot(arcsec, (x, -2, 2), exclude=[1.5]) # x=1.5 is also excluded Graphics object consisting of 3 graphics primitives .. PLOT:: set_verbose(-1) g = plot(arcsec, (x, -2, 2), exclude=[1.5]) sphinx_plot(g) :: sage: plot(arcsec(x/2), -2, 2) # plot should be empty; no valid points Graphics object consisting of 0 graphics primitives sage: plot(sqrt(x^2-1), -2, 2) # [-1, 1] is excluded automatically Graphics object consisting of 2 graphics primitives .. PLOT:: set_verbose(-1) g = plot(sqrt(x**2-1), -2, 2) sphinx_plot(g) :: sage: plot(arccsc, -2, 2) # [-1, 1] is excluded automatically Graphics object consisting of 2 graphics primitives sage: set_verbose(0) .. PLOT:: set_verbose(-1) g = plot(arccsc, -2, 2) sphinx_plot(g) TESTS: We do not randomize the endpoints:: sage: p = plot(x, (x,-1,1)) sage: p[0].xdata[0] == -1 True sage: p[0].xdata[-1] == 1 True We check to make sure that the x/y min/max data get set correctly when there are multiple functions. :: sage: d = plot([s[...]
help(solve)
Help on function solve in module sage.symbolic.relation: solve(f, *args, **kwds) Algebraically solve an equation or system of equations (over the complex numbers) for given variables. Inequalities and systems of inequalities are also supported. INPUT: - ``f`` - equation or system of equations (given by a list or tuple) - ``*args`` - variables to solve for. - ``solution_dict`` - bool (default: False); if True or non-zero, return a list of dictionaries containing the solutions. If there are no solutions, return an empty list (rather than a list containing an empty dictionary). Likewise, if there's only a single solution, return a list containing one dictionary with that solution. There are a few optional keywords if you are trying to solve a single equation. They may only be used in that context. - ``multiplicities`` - bool (default: False); if True, return corresponding multiplicities. This keyword is incompatible with ``to_poly_solve=True`` and does not make any sense when solving inequalities. - ``explicit_solutions`` - bool (default: False); require that all roots be explicit rather than implicit. Not used when solving inequalities. - ``to_poly_solve`` - bool (default: False) or string; use Maxima's ``to_poly_solver`` package to search for more possible solutions, but possibly encounter approximate solutions. This keyword is incompatible with ``multiplicities=True`` and is not used when solving inequalities. Setting ``to_poly_solve`` to 'force' (string) omits Maxima's solve command (useful when some solutions of trigonometric equations are lost). - ``algorithm`` - string (default: 'maxima'); to use SymPy's solvers set this to 'sympy'. Note that SymPy is always used for diophantine equations. Another choice is 'giac'. - ``domain`` - string (default: 'complex'); setting this to 'real' changes the way SymPy solves single equations; inequalities are always solved in the real domain. EXAMPLES:: sage: x, y = var('x, y') sage: solve([x+y==6, x-y==4], x, y) [[x == 5, y == 1]] sage: solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y) [[x == -1/2*I*sqrt(3) - 1/2, y == -sqrt(-1/2*I*sqrt(3) + 3/2)], [x == -1/2*I*sqrt(3) - 1/2, y == sqrt(-1/2*I*sqrt(3) + 3/2)], [x == 1/2*I*sqrt(3) - 1/2, y == -sqrt(1/2*I*sqrt(3) + 3/2)], [x == 1/2*I*sqrt(3) - 1/2, y == sqrt(1/2*I*sqrt(3) + 3/2)], [x == 0, y == -1], [x == 0, y == 1]] sage: solve([sqrt(x) + sqrt(y) == 5, x + y == 10], x, y) [[x == -5/2*I*sqrt(5) + 5, y == 5/2*I*sqrt(5) + 5], [x == 5/2*I*sqrt(5) + 5, y == -5/2*I*sqrt(5) + 5]] sage: solutions = solve([x^2+y^2 == 1, y^2 == x^3 + x + 1], x, y, solution_dict=True) sage: for solution in solutions: print("{} , {}".format(solution[x].n(digits=3), solution[y].n(digits=3))) -0.500 - 0.866*I , -1.27 + 0.341*I -0.500 - 0.866*I , 1.27 - 0.341*I -0.500 + 0.866*I , -1.27 - 0.341*I -0.500 + 0.866*I , 1.27 + 0.341*I 0.000 , -1.00 0.000 , 1.00 Whenever possible, answers will be symbolic, but with systems of equations, at times approximations will be given by Maxima, due to the underlying algorithm:: sage: sols = solve([x^3==y,y^2==x], [x,y]); sols[-1], sols[0] # abs tol 1e-15 ([x == 0, y == 0], [x == (0.3090169943749475 + 0.9510565162951535*I), y == (-0.8090169943749475 - 0.5877852522924731*I)]) sage: sols[0][0].rhs().pyobject().parent() Complex Double Field sage: solve([y^6==y],y) [y == 1/4*sqrt(5) + 1/4*I*sqrt(2*sqrt(5) + 10) - 1/4, y == -1/4*sqrt(5) + 1/4*I*sqrt(-2*sqrt(5) + 10) - 1/4, y == -1/4*sqrt(5) - 1/4*I*sqrt(-2*sqrt(5) + 10) - 1/4, y == 1/4*sqrt(5) - 1/4*I*sqrt(2*sqrt(5) + 10) - 1/4, y == 1, y == 0] sage: solve( [y^6 == y], y)==solve( y^6 == y, y) True Here we demonstrate very basic use of the optional keywords:: sage: ((x^2-1)^2).solve(x) [x == -1, x == 1] sage: ((x^2-1)^2).solve(x,multiplicities=True) ([x == -1, x == 1], [2, 2]) sage: solve(sin(x)==x,x) [x == sin(x)] sage: solve(sin(x)==x,x,explicit_solutions=True) [] sage: solve(abs(1-abs(1-x)) == 10, x) [abs(abs(x - 1) - 1) == 10] sage: solve(abs(1-abs(1-x)) == 10, x, to_poly_solve=True) [x == -10, x == 12] sage: from sage.symbolic.expression import Expression sage: Expression.solve(x^2==1,x) [x == -1, x == 1] We must solve with respect to actual variables:: sage: z = 5 sage: solve([8*z + y == 3, -z +7*y == 0],y,z) Traceback (most recent call last): ... TypeError: 5 is not a valid variable. If we ask for dictionaries containing the solutions, we get them:: sage: solve([x^2-1],x,solution_dict=True) [{x: -1}, {x: 1}] sage: solve([x^2-4*x+4],x,solution_dict=True) [{x: 2}] sage: res = solve([x^2 == y, y == 4],x,y,solution_dict=True) sage: for soln in res: print("x: %s, y: %s" % (soln[x], soln[y])) x: 2, y: 4 x: -2, y: 4 If there is a parameter in the answer, that will show up as a new variable. In the following example, ``r1`` is an arbitrary constant (because of the ``r``):: sage: forget() sage: x, y = var('x,y') sage: solve([x+y == 3, 2*x+2*y == 6],x,y) [[x == -r1 + 3, y == r1]] sage: var('b, c') (b, c) sage: solve((b-1)*(c-1), [b,c]) [[b == 1, c == r...], [b == r..., c == 1]] Especially with trigonometric functions, the dummy variable may be implicitly an integer (hence the ``z``):: sage: solve( sin(x)==cos(x), x, to_poly_solve=True) [x == 1/4*pi + pi*z...] sage: solve([cos(x)*sin(x) == 1/2, x+y == 0],x,y) [[x == 1/4*pi + pi*z..., y == -1/4*pi - pi*z...]] Expressions which are not equations are assumed to be set equal to zero, as with `x` in the following example:: sage: solve([x, y == 2],x,y) [[x == 0, y == 2]] If ``True`` appears in the list of equations it is ignored, and if ``False`` appears in the list then no solutions are returned. E.g., note that the first ``3==3`` evaluates to ``True``, not to a symbolic equation. :: sage: solve([3==3, 1.00000000000000*x^3 == 0], x) [x == 0] sage: solve([1.00000000000000*x^3 == 0], x) [x == 0] Here, the first equation evaluates to ``False``, so there are no solutions:: sage: solve([1==3, 1.00000000000000*x^3 == 0], x) [] Completely symbolic solutions are supported:: sage: var('s,j,b,m,g') (s, j, b, m, g) sage: sys = [ m*(1-s) - b*s*j, b*s*j-g*j ] sage: solve(sys,s,j) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,(s,j)) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: solve(sys,[s,j]) [[s == 1, j == 0], [s == g/b, j == (b - g)*m/(b*g)]] sage: z = var('z') sage: solve((x-z)^2==2, x) [x == z - sqrt(2), x == z + sqrt(2)] Inequalities can be also solved:: sage: solve(x^2>8,x) [[x < -2*sqrt(2)], [x > 2*sqrt(2)]] sage: x,y = var('x,y'); (ln(x)-ln(y)>0).solve(x) [[log(x) - log(y) > 0]] sage: x,y = var('x,y'); (ln(x)>ln(y)).solve(x) # random [[0 < y, y < x, 0 < x]] [[y < x, 0 < y]] A simple example to show the use of the keyword ``multiplicities``:: sage: ((x^2-1)^2).solve(x) [x == -1, x == 1] sage: ((x^2-1)^2).solve(x,multiplicities=True) ([x == -1, x == 1], [2, 2]) sage: ((x^2-1)^2).solve(x,multiplicities=True,to_poly_solve=True) Traceback (most recent call last): ... NotImplementedError: to_poly_solve does not return multiplicities Here is how the ``explicit_solutions`` keyword functions:: sage: solve(sin(x)==x,x) [x == sin(x)] sage: solve(sin(x)==x,x,explicit_solutions=True) [] sage: solve(x*sin(x)==x^2,x) [x == 0, x == sin(x)] sage: solve(x*sin(x)==x^2,x,explicit_solutions=True) [x == 0] The following examples show the use of the keyword ``to_poly_solve``:: sage: solve(abs(1-abs(1-x)) == 10, x) [abs(abs(x - 1) - 1) == 10] sage: solve(abs(1-abs(1-x)) == 10, x, to_poly_solve=True) [x == -10, x == 12] sage: var('Q') Q sage: solve(Q*sqrt(Q^2 + 2) - 1, Q) [Q == 1/sqrt(Q^2 + 2)] The following example is a regression in Maxima 5.39.0. It used to be possible to get one more solution here, namely ``1/sqrt(sqrt(2) + 1)``, see https://sourceforge.net/p/maxima/bugs/3276/:: sage: solve(Q*sqrt(Q^2 + 2) - 1, Q, to_poly_solve=True) [Q == -sqrt(-sqrt(2) - 1), Q == sqrt(sqrt(2) + 1)*(sqrt(2) - 1)] An effort is made to only return solutions that satisfy the current assumptions:: sage: solve(x^2==4, x) [x == -2, x == 2] sage: assume(x<0) sage: solve(x^2==4, x) [x == -2] sage: solve((x^2-4)^2 == 0, x, multiplicities=True) ([x == -2], [2]) sage: solve(x^2==2, x) [x == -sqrt(2)] sage: z = var('z') sage: solve(x^2==2-z, x) [x == -sqrt(-z + 2)] sage: assume(x, 'rational') sage: solve(x^2 == 2, x) [] In some cases it may be worthwhile to directly use ``to_poly_solve`` if one suspects some answers are being missed:: sage: forget() sage: solve(cos(x)==0, x) [x == 1/2*pi] sage: solve(cos(x)==0, x, to_poly_solve=True) [x == 1/2*pi] sage: solve(cos(x)==0, x, to_poly_solve='force') [x == 1/2*pi + pi*z...] The same may also apply if a returned unsolved expression has a denominator, but the original one did not:: sage: solve(cos(x) * sin(x) == 1/2, x, to_poly_solve=True) [sin(x) == 1/2/cos(x)] sage: solve(cos(x) * sin(x) == 1/2, x, to_poly_solve=True, explicit_solutions=True) [x == 1/4*pi + pi*z...] sage: solve(cos(x) * sin(x) == 1/2, x, to_poly_solve='force') [x == 1/4*pi + pi*z...] We use ``use_grobner`` in Maxima if no solution is obtained from Maxima's ``to_poly_solve``:: sage: x,y = var('x y') sage: c1(x,y) = (x-5)^2+y^2-16 sage: c2(x,y) = (y-3)^2+x^2-9 sage: solve([c1(x,y),c2(x,y)],[x,y]) [[x == -9/68*sqrt(55) + 135/68, y == -15/68*sqrt(55) + 123/68], [x == 9/68*sqrt(55) + 135/68, y == 15/68*sqrt(55) + 123/68]] We use SymPy for Diophantine equations, see ``Expression.solve_diophantine``:: sage: assume(x, 'integer') sage: assume(z, 'integer') sage: solve((x-z)^2==2, x) [] sage: forget() The following shows some more of SymPy's capabilities that cannot be handled by Maxima:: sage: _ = var('t') sage: r = solve([x^2 - y^2/exp(x), y-1], x, y, algorithm='sympy') sage: (r[0][x], r[0][y]) (2*lambert_w(-1/2), 1) sage: solve(-2*x**3 + 4*x**2 - 2*x + 6 > 0, x, algorithm='sympy') [x < 1/3*(1/2)^(1/3)*(9*sqrt(77) + 79)^(1/3) + 2/3*(1/2)^(2/3)/(9*sqrt(77) + 79)^(1/3) + 2/3] sage: solve(sqrt(2*x^2 - 7) - (3 - x),x,algorithm='sympy') [x == -8, x == 2] sage: solve(sqrt(2*x + 9) - sqrt(x + 1) - sqrt(x + 4),x,algorithm='sympy') [x == 0] sage: r = solve([x + y + z + t, -z - t], x, y, z, t, algorithm='sympy') sage: (r[0][x], r[0][z]) (-y, -t) sage: r = solve([x^2+y+z, y+x^2+z, x+y+z^2], x, y,z, algorithm='sympy') sage: (r[0][x], r[0][y]) (z, -(z + 1)*z) sage: (r[1][x], r[1][y]) (-z + 1, -z^2 + z - 1) sage: solve(abs(x + 3) - 2*abs(x - 3),x,algorithm='sympy',domain='real') [x == 1, x == 9] We cannot translate all results from SymPy but we can at least print them:: sage: solve(sinh(x) - 2*cosh(x),x,algorithm='sympy') [ImageSet(Lambda(_n, I*(2*_n*pi + pi/2) + log(sqrt(3))), Integers), ImageSet(Lambda(_n, I*(2*_n*pi - pi/2) + log(sqrt(3))), Integers)] sage: solve(2*sin(x) - 2*sin(2*x), x,algorithm='sympy') [ImageSet(Lambda(_n, 2*_n*pi), Integers), ImageSet(Lambda(_n, 2*_n*pi + pi), Integers), ImageSet(Lambda(_n, 2*_n*pi + 5*pi/3), Integers), ImageSet(Lambda(_n, 2*_n*pi + pi/3), Integers)] sage: solve(x^5 + 3*x^3 + 7, x, algorithm='sympy')[0] # known bug complex_root_of(x^5 + 3*x^3 + 7, 0) A basic interface to Giac is provided:: sage: solve([(2/3)^x-2], [x], algorithm='giac') ...[[-log(2)/(log(3) - log(2))]] sage: f = (sin(x) - 8*cos(x)*sin(x))*(sin(x)^2 + cos(x)) - (2*cos(x)*sin(x) - sin(x))*(-2*sin(x)^2 + 2*cos(x)^2 - cos(x)) sage: solve(f, x, algorithm='giac') ...[-2*arctan(sqrt(2)), 0, 2*arctan(sqrt(2)), pi] sage: x, y = SR.var('x,y') sage: solve([x+y-4,x*y-3],[x,y],algorithm='giac') [[1, 3], [3, 1]] TESTS:: sage: solve([sin(x)==x,y^2==x],x,y) [sin(x) == x, y^2 == x] sage: solve(0==1,x) Traceback (most recent call last): ... TypeError: The first argument must be a symbolic expression or a list of symbolic expressions. Test if the empty list is returned, too, when (a list of) dictionaries (is) are requested (:trac:`8553`):: sage: solve([SR(0)==1],x) [] sage: solve([SR(0)==1],x,solution_dict=True) [] sage: solve([x==1,x==-1],x) [] sage: solve([x==1,x==-1],x,solution_dict=True) [] sage: solve((x==1,x==-1),x,solution_dict=0) [] Relaxed form, suggested by Mike Hansen (:trac:`8553`):: sage: solve([x^2-1],x,solution_dict=-1) [{x: -1}, {x: 1}] sage: solve([x^2-1],x,solution_dict=1) [{x: -1}, {x: 1}] sage: solve((x==1,x==-1),x,solution_dict=-1) [] sage: solve((x==1,x==-1),x,solution_dict=1) [] This inequality holds for any real ``x`` (:trac:`8078`):: sage: solve(x^4+2>0,x) [x < +Infinity] Test for user friendly input handling :trac:`13645`:: sage: poly.<a,b> = PolynomialRing(RR) sage: solve([a+b+a*b == 1], a) Traceback (most recent call last): ... TypeError: a is not a valid variable. sage: a,b = var('a,b') sage: solve([a+b+a*b == 1], a) [a == -(b - 1)/(b + 1)] sage: solve([a, b], (1, a)) Traceback (most recent call last): ... TypeError: 1 is not a valid variable. sage: solve([x == 1], (1, a)) Traceback (most recent call last): ... TypeError: 1 is not a valid variable. sage: x.solve((1,2)) Traceback (most recent call last): ... TypeError: 1 is not a valid variable. Test that the original version of a system in the French Sage book now works (:trac:`14306`):: sage: var('y,z') (y, z) sage: solve([x^2 * y * z == 18, x * y^3 * z == 24, x * y * z^4 == 6], x, y, z) [[x == 3, y == 2, z == 1], [x == (1.337215067... - 2.685489874...*I), y == (-1.700434271... + 1.052864325...*I), z == (0.9324722294... - 0.3612416661...*I)], ...] :trac:`13286` fixed:: sage: solve([x-4], [x]) [x == 4] Test for a list of non-symbolic expressions as first argument (:trac:`31714`):: sage: solve([1], x) Traceback (most recent call last): ... TypeError: The first argument to solve() should be a symbolic expression or a list of symbolic expressions.
t=var('t') x=cos(t)+1 y=sin(2*t) p=parametric_plot([x,y],(t,0,pi))+plot(y,(t,0,pi),fill=0) p.show() f(x)=4*cos(4*x) f(x).integral(x,0,pi/12,hold=True).show()
0112π4cos(4x)dx\displaystyle \int_{0}^{\frac{1}{12} \, \pi} 4 \, \cos\left(4 \, x\right)\,{d x}
x, y = var('x, y') p1=plot(sqrt(y),0,9,fill=3,axes_labels=['$y$','$x$']) p2=plot(3,0,9) R=p1+p2 R.show(aspect_ratio=1) assume(0<y<9) F=sin(pi*x^3) a=F.integral(y,0,x^2,hold=True).integral(x,0,3,hold=True) show(a) show(a.unhold())
030x2sin(πx3)dydx\displaystyle \int_{0}^{3} \int_{0}^{x^{2}} \sin\left(\pi x^{3}\right)\,{d y}\,{d x}
23π\displaystyle \frac{2}{3 \, \pi}
bool(e^(I*x)==cos(x)+I*sin(x))
True
L=[] while len(L)<100: n=1 if len(n.factor())==4: L.append(n) n+=1 print(L)
Error in lines 2-6 Traceback (most recent call last): File "/cocalc/lib/python3.11/site-packages/smc_sagews/sage_server.py", line 1244, in execute exec( File "", line 3, in <module> File "sage/rings/integer.pyx", line 3954, in sage.rings.integer.Integer.factor return IntegerFactorization([], unit=unit, unsafe=True, File "/ext/sage/10.1/src/sage/structure/factorization_integer.py", line 30, in __init__ def __init__(self, x, unit=None, cr=False, sort=True, simplify=True, File "src/cysignals/signals.pyx", line 310, in cysignals.signals.python_check_interrupt KeyboardInterrupt
60.factor()
2^2 * 3 * 5
t= var('t') x, y=cos(t)^3, sin(t)^3 p=parametric_plot([x,y], (t,0,2*pi)) p.show(frame=False,axes=False, aspect_ratio=1) F=sqrt(x.diff(t)^2+y.diff(t)^2).simplify() F.integral(t,0,2*pi).show()
6\displaystyle 6
L=[] n=1 while len(L)<100: if len(n.factor())==4: L.append(n) n+=1 print(L) print(len(L))
[210, 330, 390, 420, 462, 510, 546, 570, 630, 660, 690, 714, 770, 780, 798, 840, 858, 870, 910, 924, 930, 966, 990, 1020, 1050, 1092, 1110, 1122, 1140, 1155, 1170, 1190, 1218, 1230, 1254, 1260, 1290, 1302, 1320, 1326, 1330, 1365, 1380, 1386, 1410, 1428, 1430, 1470, 1482, 1518, 1530, 1540, 1554, 1560, 1590, 1596, 1610, 1638, 1650, 1680, 1710, 1716, 1722, 1740, 1770, 1785, 1794, 1806, 1820, 1830, 1848, 1860, 1870, 1890, 1914, 1932, 1938, 1950, 1974, 1980, 1995, 2002, 2010, 2030, 2040, 2046, 2070, 2090, 2100, 2130, 2142, 2145, 2170, 2184, 2190, 2210, 2220, 2226, 2244, 2262] 100
x,y=var('x,y') F=x^(2/3)+y^(2/3)==1 show((1-x^(2/3))^(3/2).integral(x,0,1))
Error in lines 3-3 Traceback (most recent call last): File "/cocalc/lib/python3.11/site-packages/smc_sagews/sage_server.py", line 1244, in execute exec( File "", line 1, in <module> File "sage/structure/element.pyx", line 488, in sage.structure.element.Element.__getattr__ return self.getattr_from_category(name) File "sage/structure/element.pyx", line 501, in sage.structure.element.Element.getattr_from_category return getattr_from_other_class(self, cls, name) File "sage/cpython/getattr.pyx", line 362, in sage.cpython.getattr.getattr_from_other_class raise AttributeError(dummy_error_message) AttributeError: 'sage.rings.rational.Rational' object has no attribute 'integral'
x,y,a=var('x,y,a') f=(x+y)^2 f.integral(x,abs(y),a).integral(y,-a,a).show()
23a4sgn(a)+43a4\displaystyle -\frac{2}{3} \, a^{4} \mathrm{sgn}\left(a\right) + \frac{4}{3} \, a^{4}
x,y=var('x,y') f=(x-1)*(1+exp(2*y))^(1/2) f.integral(y,0,ln(x),hold=True).integral(x,1,2,hold=True).show()
120log(x)(x1)e(2y)+1dydx\displaystyle \int_{1}^{2} \int_{0}^{\log\left(x\right)} {\left(x - 1\right)} \sqrt{e^{\left(2 \, y\right)} + 1}\,{d y}\,{d x}
x,y=var('x,y') f=(x-1)*(1+exp(2*y))^(1/2) f.integral(x,exp(y),2).integral(y,0,ln(2)).show()
165162+14log(125+1)14log(1251)14log(2+1)+14log(21)\displaystyle \frac{1}{6} \, \sqrt{5} - \frac{1}{6} \, \sqrt{2} + \frac{1}{4} \, \log\left(\frac{1}{2} \, \sqrt{5} + 1\right) - \frac{1}{4} \, \log\left(\frac{1}{2} \, \sqrt{5} - 1\right) - \frac{1}{4} \, \log\left(\sqrt{2} + 1\right) + \frac{1}{4} \, \log\left(\sqrt{2} - 1\right)
x,y,z,t=var('x,y,z,t') p=implicit_plot3d(x^2+y^2==1, (x,-2,2),(y,-2,2),(z,-2,3),opacity=0.1,color='yellow') p+=implicit_plot3d(z==y+1,(x,-2,2),(y,-2,2),(z,-2,3),opacity=0.1,color='red') p+=parametric_plot3d((cos(t),sin(t),sin(t)+1),(0,2*pi)) p.show()
3D rendering not yet implemented
x,y,z,t=var('x,y,z,t') x,y,z=cos(t),sin(t),y+1 f=(4*z)*x.diff(t)-(3*x)*y.diff(t)+(2*x)*z.diff(t) integrate(f,(t,0,2*pi))
-3*pi
x,y=var('x,y') X(x,y)=cos(x)*sin(y)-x*y Y(x,y)=sin(x)*cos(y)+x^3 F=Y.diff(x)-X.diff(y) f=F(x,y) integrate(integrate(f,(x,0,pi)),(y,0,1))
pi^3 + 1/2*pi^2
a=1/(x*(x+1)^3*(x^2+2)^2) a.partial_fraction().show()
9x8108(x2+2)+5x254(x2+2)213(x+1)+14x727(x+1)219(x+1)3\displaystyle \frac{9 \, x - 8}{108 \, {\left(x^{2} + 2\right)}} + \frac{5 \, x - 2}{54 \, {\left(x^{2} + 2\right)}^{2}} - \frac{1}{3 \, {\left(x + 1\right)}} + \frac{1}{4 \, x} - \frac{7}{27 \, {\left(x + 1\right)}^{2}} - \frac{1}{9 \, {\left(x + 1\right)}^{3}}
x,y,z=var('x,y,z') eq1=x+y+z==0 eq2=y+z==0 s=solve([eq1,eq2],[x,y,z]) s
[[x == 0, y == -r1, z == r1]]
help(det)
Help on function det in module sage.misc.functional: det(x) Return the determinant of ``x``. EXAMPLES:: sage: M = MatrixSpace(QQ,3,3) sage: A = M([1,2,3,4,5,6,7,8,9]) sage: det(A) 0
x=det(matrix(3,3,[1,1,1,2,-1,2,5,-1,6]))/det(matrix(3,3,[1,1,1,1,-1,2,3,-1,6]))
det(matrix(2,2,[2,3,4,5]))
-2
x,x1,x2=var('x,x1,x2') det(matrix(3,3,[1,x,x^2,1,x1,(x1)^2,1,x2,(x2)^2])).show()
x2x1+xx12+x2x2x12x2xx22+x1x22\displaystyle -x^{2} x_{1} + x x_{1}^{2} + x^{2} x_{2} - x_{1}^{2} x_{2} - x x_{2}^{2} + x_{1} x_{2}^{2}
Error in lines 2-2 Traceback (most recent call last): File "/cocalc/lib/python3.11/site-packages/smc_sagews/sage_server.py", line 1244, in execute exec( File "", line 1, in <module> AttributeError: 'NoneType' object has no attribute 'factor'
A= matrix(9,lambda i,j: 1/(i+j+1)) show(A)
(11213141516171819121314151617181911013141516171819110111141516171819110111112151617181911011111211316171819110111112113114171819110111112113114115181911011111211311411511619110111112113114115116117)\displaystyle \left(\begin{array}{rrrrrrrrr} 1 & \frac{1}{2} & \frac{1}{3} & \frac{1}{4} & \frac{1}{5} & \frac{1}{6} & \frac{1}{7} & \frac{1}{8} & \frac{1}{9} \\ \frac{1}{2} & \frac{1}{3} & \frac{1}{4} & \frac{1}{5} & \frac{1}{6} & \frac{1}{7} & \frac{1}{8} & \frac{1}{9} & \frac{1}{10} \\ \frac{1}{3} & \frac{1}{4} & \frac{1}{5} & \frac{1}{6} & \frac{1}{7} & \frac{1}{8} & \frac{1}{9} & \frac{1}{10} & \frac{1}{11} \\ \frac{1}{4} & \frac{1}{5} & \frac{1}{6} & \frac{1}{7} & \frac{1}{8} & \frac{1}{9} & \frac{1}{10} & \frac{1}{11} & \frac{1}{12} \\ \frac{1}{5} & \frac{1}{6} & \frac{1}{7} & \frac{1}{8} & \frac{1}{9} & \frac{1}{10} & \frac{1}{11} & \frac{1}{12} & \frac{1}{13} \\ \frac{1}{6} & \frac{1}{7} & \frac{1}{8} & \frac{1}{9} & \frac{1}{10} & \frac{1}{11} & \frac{1}{12} & \frac{1}{13} & \frac{1}{14} \\ \frac{1}{7} & \frac{1}{8} & \frac{1}{9} & \frac{1}{10} & \frac{1}{11} & \frac{1}{12} & \frac{1}{13} & \frac{1}{14} & \frac{1}{15} \\ \frac{1}{8} & \frac{1}{9} & \frac{1}{10} & \frac{1}{11} & \frac{1}{12} & \frac{1}{13} & \frac{1}{14} & \frac{1}{15} & \frac{1}{16} \\ \frac{1}{9} & \frac{1}{10} & \frac{1}{11} & \frac{1}{12} & \frac{1}{13} & \frac{1}{14} & \frac{1}{15} & \frac{1}{16} & \frac{1}{17} \end{array}\right)
x=SR.var('x',5); x A=matrix(5,5,lambda i,j:x[i]^j) show(A) A.det().factor()
(x0, x1, x2, x3, x4)
(1x0x02x03x041x1x12x13x141x2x22x23x241x3x32x33x341x4x42x43x44)\displaystyle \left(\begin{array}{rrrrr} 1 & x_{0} & x_{0}^{2} & x_{0}^{3} & x_{0}^{4} \\ 1 & x_{1} & x_{1}^{2} & x_{1}^{3} & x_{1}^{4} \\ 1 & x_{2} & x_{2}^{2} & x_{2}^{3} & x_{2}^{4} \\ 1 & x_{3} & x_{3}^{2} & x_{3}^{3} & x_{3}^{4} \\ 1 & x_{4} & x_{4}^{2} & x_{4}^{3} & x_{4}^{4} \end{array}\right)
(x0 - x1)*(x0 - x2)*(x0 - x3)*(x0 - x4)*(x1 - x2)*(x1 - x3)*(x1 - x4)*(x2 - x3)*(x2 - x4)*(x3 - x4)
A= matrix(5,5,[1,1,2,1,1, 1,2,3,2,1, 2,3,1,2,1, 1,2,2,3,1, 1,1,1,1,7]) B=A.charpoly() for v in A.eigenvectors_right(): print("eigenvalue",v[0])
eigenvalue -1.898437229647213? eigenvalue 0.3126193021869149? eigenvalue 1.071200945566419? eigenvalue 5.280735607688378? eigenvalue 9.23388137420550?
A=matrix(3,3,[1,2,3,4,5,6,7,8,9]) B=matrix(3,3,[1,3,4,5,6,6,6,6,6]) C=matrix(2,2,[1,1,0,1])
[e e] [0 e]
a= all([True,True,True,True]) b= all([True,False,True,True]) c= any([False,False,False,False]) d= any([False,False,True,False]) print(a,b,c,d)
True False False True
a=(1==1) print(a)
True
list(filter(lambda n: is_prime(2^n-1), range(100)))
[2, 3, 5, 7, 13, 17, 19, 31, 61, 89]
all([is_prime(j) for j in range(1000) if is_prime(2^j-1)])
True
all([is_prime(2^p-1) for p in range(1000) if is_prime(p)])
False
forall([j for j in srange(1000) if is_prime(j)], lambda x : is_prime(2^x-1))
(False, 11)
exists([j for j in srange(1000) if is_prime(j)], lambda x : not is_prime(2^x-1))
(True, 11)
print(s for s in range(0,100))
<generator object <genexpr> at 0x7f929f1cd490>
exists([(x,y) for x in range(200) for y in range(200)], lambda z: 3*z[0]+5*z[1]==71)
(True, (2, 13))
exists([(x,y) for x in range(200) for y in range(200)], lambda z : z[0]^3+z[1]^3==218)
(False, None)
list(filter(lambda x: x<6, [17,2,5,9,2,3,6]))
[2, 5, 2, 3]
L=[3,7,6,2,5] reduce(lambda x,y: 10*int(x)+int(y),L)
37625
B=Permutations([1,2,3]) B
Standard permutations of 3
n=323431 list2int = lambda L: reduce(lambda x, y: 10*x+y)
Error in lines 1-1 Traceback (most recent call last): File "/cocalc/lib/python3.11/site-packages/smc_sagews/sage_server.py", line 1244, in execute exec( File "", line 1, in <module> File "sage/structure/element.pyx", line 488, in sage.structure.element.Element.__getattr__ return self.getattr_from_category(name) File "sage/structure/element.pyx", line 501, in sage.structure.element.Element.getattr_from_category return getattr_from_other_class(self, cls, name) File "sage/cpython/getattr.pyx", line 362, in sage.cpython.getattr.getattr_from_other_class raise AttributeError(dummy_error_message) AttributeError: 'sage.rings.integer.Integer' object has no attribute 'digit'
a= list(graphs(5, lambda G: G.size() <=4)) show(*a)
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
d3-based renderer not yet implemented
a=Graph({0:[1,2,3,4,5,6,7]}) a.plot().show() b=a.to_directed() b.plot().show() c=DiGraph({0:[1,2,3,4,5,6,7], 1: [0], 2: [0]}) c.plot().show()
a=matrix( [[1,0,2], [0,2,3], [2,3,5]]) b=Graph(a) b.plot().show()
sum([len(n.factor()) for n in [2..10]])
11
L=[n for n in [1..10] if not [e for p, e in n.factor() if e>1]] print(L)
[1, 2, 3, 5, 6, 7, 10]
[n for n in [10..15] if sum(n.divisors())>2*n]
[12]
f(x)=4*cos(4*x) a=f(x).integral(x,0,pi/12,hold=True) show(a==a.unhold())
0112π4cos(4x)dx=123\displaystyle \int_{0}^{\frac{1}{12} \, \pi} 4 \, \cos\left(4 \, x\right)\,{d x} = \frac{1}{2} \, \sqrt{3}
def meansort(*L): if not L: return tuple([]) m= sum(L)/len(L) M=[(abs(x-m), n, x) for n,x in enumerate(L)] M.sort() return tuple(c for (a,b,c) in M) meansort(1,-1,-2,2,0)
(0, 1, -1, -2, 2)
A = matrix((4,4), lambda i,j : 1/(i+j+1)) show(A)
Error in lines 1-1 Traceback (most recent call last): File "/cocalc/lib/python3.11/site-packages/smc_sagews/sage_server.py", line 1244, in execute exec( File "", line 1, in <module> File "sage/matrix/constructor.pyx", line 643, in sage.matrix.constructor.matrix M = MatrixArgs(*args, **kwds).matrix() File "sage/matrix/args.pyx", line 356, in sage.matrix.args.MatrixArgs.__init__ raise TypeError("too many arguments in matrix constructor") TypeError: too many arguments in matrix constructor
L=[5,7,6,2,3] IT=lambda L: reduce(lambda x, y: 10*x+y, L) IT(L)
57623
list(filter(lambda n: is_prime(2**n-1), range(8)))
[2, 3, 5, 7]
exists(((x,y) for x in [1..5] for y in [1..5]), lambda P: P[0]^2+P[1]^2==34)
(True, (3, 5))
g = Graph(0: [1,2,3,4]) g.plot().show()
Error in lines 1-1 Traceback (most recent call last): File "/cocalc/lib/python3.11/site-packages/smc_sagews/sage_server.py", line 1245, in execute compile(block + '\n', File "<string>", line 1 g = Graph(Integer(0): [Integer(1),Integer(2),Integer(3),Integer(4)]) ^ SyntaxError: invalid syntax
x,y,t=var('x,y,t') a= abs(x)^(2/3) + abs(y)^(2/3) ==1 p=plot.(a,(x,-1,1), (y,-1,1)) p.show()
Error in lines 3-3 Traceback (most recent call last): File "/cocalc/lib/python3.11/site-packages/smc_sagews/sage_server.py", line 1245, in execute compile(block + '\n', File "<string>", line 1 p=plot.(a,(x,-Integer(1),Integer(1)), (y,-Integer(1),Integer(1))) ^ SyntaxError: invalid syntax