OU LV 2 Priprema

  • Upload
    edhem

  • View
    218

  • Download
    0

Embed Size (px)

Citation preview

  • 8/17/2019 OU LV 2 Priprema

    1/25

     UNIVERZITET U SARAJEVU

    ELEKTROTEHNIČKI FAKULTET SARAJEVO 

    Sarajevo, mart 2014.

    Uvod u Sage

    Pripremio:Nadir Kapetanović 

  • 8/17/2019 OU LV 2 Priprema

    2/25

    Table of Contents

    1. Introduction ...................................................................................................................... 3 

    1.1. Ways to Use Sage ....................................................................................................... 3 

    1.2. Longterm Goals for Sage ............................................................................................. 3 

    2. Assignment, Equality, and Arithmetic ................................................................................ 5 

    3. Getting Help ...................................................................................................................... 7 

    4. Functions, Indentation, and Counting ................................................................................ 7 

    5. Basic Algebra and Calculus .............................................................................................. 11  

    5.1. Solving Equations Exactly .......................................................................................... 11 

    5.2. Solving Equations Numerically .................................................................................. 12 

    5.3. Differentiation, Integration, etc. ............................................................................... 12 

    5.4. Solving Differential Equations ................................................................................... 13 6. Symbolic Expressions....................................................................................................... 15 

    7. Plotting ........................................................................................................................... 18 

    7.1. Basic 2D Plotting ....................................................................................................... 18 

    7.2. Basic 3D Plotting ....................................................................................................... 22 

    7.2.1. Region plot ........................................................................................................ 23

  • 8/17/2019 OU LV 2 Priprema

    3/25

    1. Introduction

    Sage is free, open-source math software that supports research and teaching in algebra,

    geometry, number theory, cryptography, numerical computation, and related areas. Both

    the Sage development model and the technology in Sage itself are distinguished by anextremely strong emphasis on openness, community, cooperation, and collaboration: we

    are building the car, not reinventing the wheel. The overall goal of Sage is to create a viable,

    free, open-source alternative to Maple, Mathematica, Magma, and MATLAB.

    1.1. Ways to Use Sage

    You can use Sage in several ways.

      Notebook graphical interface: see the section on the Notebook in the reference

    manual and The Notebook Interface below,  Interactive command line: see The Interactive Shell , 

      Programs: By writing interpreted and compiled programs in Sage (see Loading

    and Attaching Sage files and Creating Compiled Code), and

      Scripts: by writing stand-alone Python scripts that use the Sage library

    (see Standalone Python/Sage Scripts).

    1.2. Longterm Goals for Sage

    Useful: Sage’s intended audience is mathematics students (from high school to graduateschool), teachers, and research mathematicians. The aim is to provide software that can be

    used to explore and experiment with mathematical constructions in algebra, geometry,

    number theory, calculus, numerical computation, etc. Sage helps make it easier to

    interactively experiment with mathematical objects.

    Efficient: Be fast. Sage uses highly-optimized mature software like GMP, PARI, GAP, and

    NTL, and so is very fast at certain operations.

    Free and open source: The source code must be freely available and readable, so users

    can understand what the system is really doing and more easily extend it. Just asmathematicians gain a deeper understanding of a theorem by carefully reading or at least

    skimming the proof, people who do computations should be able to understand how the

    calculations work by reading documented source code. If you use Sage to do computations

    in a paper you publish, you can rest assured that your readers will always have free access

    to Sage and all its source code, and you are even allowed to archive and re-distribute the

    version of Sage you used.

    Easy to compile: Sage should be easy to compile from source for Linux, OS X and

    Windows users. This provides more flexibility for users to modify the system.

    http://www.sagemath.org/doc/tutorial/interactive_shell.html#section-notebookhttp://www.sagemath.org/doc/tutorial/interactive_shell.html#section-notebookhttp://www.sagemath.org/doc/tutorial/interactive_shell.html#section-notebookhttp://www.sagemath.org/doc/tutorial/interactive_shell.html#chapter-interactive-shellhttp://www.sagemath.org/doc/tutorial/interactive_shell.html#chapter-interactive-shellhttp://www.sagemath.org/doc/tutorial/interactive_shell.html#chapter-interactive-shellhttp://www.sagemath.org/doc/tutorial/programming.html#section-loadattachhttp://www.sagemath.org/doc/tutorial/programming.html#section-loadattachhttp://www.sagemath.org/doc/tutorial/programming.html#section-loadattachhttp://www.sagemath.org/doc/tutorial/programming.html#section-loadattachhttp://www.sagemath.org/doc/tutorial/programming.html#section-compilehttp://www.sagemath.org/doc/tutorial/programming.html#section-compilehttp://www.sagemath.org/doc/tutorial/programming.html#section-compilehttp://www.sagemath.org/doc/tutorial/programming.html#section-standalonehttp://www.sagemath.org/doc/tutorial/programming.html#section-standalonehttp://www.sagemath.org/doc/tutorial/programming.html#section-standalonehttp://www.sagemath.org/doc/tutorial/programming.html#section-standalonehttp://www.sagemath.org/doc/tutorial/programming.html#section-compilehttp://www.sagemath.org/doc/tutorial/programming.html#section-loadattachhttp://www.sagemath.org/doc/tutorial/programming.html#section-loadattachhttp://www.sagemath.org/doc/tutorial/interactive_shell.html#chapter-interactive-shellhttp://www.sagemath.org/doc/tutorial/interactive_shell.html#section-notebook

  • 8/17/2019 OU LV 2 Priprema

    4/25

    Cooperation: Provide robust interfaces to most other computer algebra systems,

    including PARI, GAP, Singular, Maxima, KASH, Magma, Maple, and Mathematica. Sage is

    meant to unify and extend existing math software.

    Well documented: Tutorial, programming guide, reference manual, and how-to, with

    numerous examples and discussion of background mathematics.

    Extensible: Be able to define new data types or derive from built-in types, and use code

    written in a range of languages.

    User friendly: It should be easy to understand what functionality is provided for a given

    object and to view documentation and source code. Also attain a high level of user support.

  • 8/17/2019 OU LV 2 Priprema

    5/25

    2. Assignment, Equality, and Arithmetic

    With some minor exceptions, Sage uses the Python programming language, so most

    introductory books on Python will help you to learn Sage.

    Sage uses = for assignment. It uses ==, =,  for comparison:

    sage: a = 5 sage: a5 sage: 2 == 2 True sage: 2 == 3 False sage: 2 

  • 8/17/2019 OU LV 2 Priprema

    6/25

    requested number of bits of precision, and digits, which is the requested number of

    decimal digits of precision; the default is 53 bits of precision.

    sage: exp(2)e^2 sage: n(exp(2))

    7.38905609893065 sage: sqrt(pi).numerical_approx()1.77245385090552 sage: sin(10).n(digits=5)-0.54402 sage: N(sin(10),digits=10)-0.5440211109 sage: numerical_approx(pi, prec=200)

    3.1415926535897932384626433832795028841971693993751058209749  

    Python is dynamically typed, so the value referred to by each variable has a type associated

    with it, but a given variable may hold values of any Python type within a given scope:

    sage: a = 5  # a is an integer  sage: type(a) sage: a = 5/3  # now a is a rational number  sage: type(a) sage: a = 'hello'  # now a is a string  sage: type(a)

     

    The C programming language, which is statically typed, is much different; a variable

    declared to hold an int can only hold an int in its scope.

    A potential source of confusion in Python is that an integer literal that begins with a zero is

    treated as an octal number, i.e., a number in base 8.

    sage: 011 9 sage: 8 + 1 9 sage: n = 011 sage: n.str(8) # string representation of n in base 8 

    '11' 

    This is consistent with the C programming language.

  • 8/17/2019 OU LV 2 Priprema

    7/25

    3. Getting Help

    Sage has extensive built-in documentation, accessible by typing the name of a function or a

    constant (for example), followed by a question mark:

    sage: tan?Type: Definition: tan( [noargspec] )Docstring:

    The tangent function

    EXAMPLES:sage: tan(pi)0sage: tan(3.1415)-0.0000926535900581913sage: tan(3.1415/4)

    0.999953674278156sage: tan(pi/4)1sage: tan(1/2)tan(1/2)sage: RR(tan(1/2))0.546302489843790

    Sage also provides ‘Tab completion’: type the first few letters of a function and then hit the

    tab key. For example, if you type ta followed by TAB, Sage will

    print tachyon, tan, tanh, taylor. This provides a good way to find the names of

    functions and other structures in Sage.

    4. Functions, Indentation, and Counting

    To define a new function in Sage, use the def command and a colon after the list of

    variable names. For example:

    sage: def is_even(n):... return n%2 == 0 ... 

    sage: is_even(2)True sage: is_even(3)

    False 

    Note: Depending on which version of the tutorial you are viewing, you may see three

    dots ... on the second line of this example. Do not type them; they are just to emphasize

    that the code is indented. Whenever this is the case, press [Return/Enter] once at the end of

    the block to insert a blank line and conclude the function definition.

    You do not specify the types of any of the input arguments. You can specify multiple inputs,

    each of which may have an optional default value. For example, the function below defaults

    to divisor=2 if  divisor is not specified.

  • 8/17/2019 OU LV 2 Priprema

    8/25

    sage: def is_divisible_by(number, divisor=2):... return number%divisor == 0 sage: is_divisible_by(6,2)True sage: is_divisible_by(6)True sage: is_divisible_by(6, 5)False 

    You can also explicitly specify one or either of the inputs when calling the function; if you

    specify the inputs explicitly, you can give them in any order:

    sage: is_divisible_by(6, divisor=5)False sage: is_divisible_by(divisor=2, number=6)

    True 

    In Python, blocks of code are not indicated by curly braces or begin and end blocks as inmany other languages. Instead, blocks of code are indicated by indentation, which must

    match up exactly. For example, the following is a syntax error because

    the return statement is not indented the same amount as the other lines above it.

    sage: def even(n):... v = []... for i in range(3,n):... if i % 2 == 0:... v.append(i)... return vSyntax Error: 

    return v 

    If you fix the indentation, the function works:

    sage: def even(n):... v = []... for i in range(3,n):... if i % 2 == 0:... v.append(i)... return vsage: even(10)

    [4, 6, 8] 

    Semicolons are not needed at the ends of lines; a line is in most cases ended by a newline.

    However, you can put multiple statements on one line, separated by semicolons:

    sage: a = 5; b = a + 3; c = b^2; c64 

    If you would like a single line of code to span multiple lines, use a terminating backslash:

    sage: 2 + \... 3 

  • 8/17/2019 OU LV 2 Priprema

    9/25

    In Sage, you count by iterating over a range of integers. For example, the first line below is

    exactly like for(i=0; i

  • 8/17/2019 OU LV 2 Priprema

    10/25

    Use len(v) to get the length of  v, use v.append(obj) to append a new object to the

    end of  v, and use del v[i] to delete the ith entry of  v:sage: len(v)4 sage: v.append(1.5)

    sage: v[1, 'hello', 2/3, sin(x^3), 1.50000000000000] sage: del v[1]sage: v

    [1, 2/3, sin(x^3), 1.50000000000000] 

    You can also define new data types using classes. Encapsulating mathematical objects with

    classes is a powerful technique that can help to simplify and organize your Sage programs.

  • 8/17/2019 OU LV 2 Priprema

    11/25

    5. Basic Algebra and Calculus

    Sage can perform various computations related to basic algebra and calculus: for example,

    finding solutions to equations, differentiation, integration, and Laplace transforms. See

    the Sage Constructionsdocumentation for more examples.

    5.1. Solving Equations Exactly

    The solve function solves equations. To use it, first specify some variables; then the

    arguments to solve are an equation (or a system of equations), together with the

    variables for which to solve:

    sage: x = var('x')sage: solve(x^2 + 3*x + 2, x)

    [x == -2, x == -1] 

    You can solve equations for one variable in terms of others:

    sage: x, b, c = var('x b c')sage: solve([x^2 + b*x + c == 0],x)

    [x == -1/2*b - 1/2*sqrt(b^2 - 4*c), x == -1/2*b + 1/2*sqrt(b^2 - 4*c)] 

    You can also solve for several variables:

    sage: x, y = var('x, y')sage: solve([x+y==6, x-y==4], x, y)

    [[x == 5, y == 1]] 

    The following example of using Sage to solve a system of non-linear equations was provided

    by Jason Grout: first, we solve the system symbolically:

    sage: var('x y p q')(x, y, p, q) sage: eq1 = p+q==9 sage: eq2 = q*y+p*x==-6 sage: eq3 = q*y^2+p*x^2==24 sage: solve([eq1,eq2,eq3,p==1],p,q,x,y)[[p == 1, q == 8, x == -4/3*sqrt(10) - 2/3, y == 1/6*sqrt(5)*sqrt(2) -2/3], 

    [p == 1, q == 8, x == 4/3*sqrt(10) - 2/3, y == -1/6*sqrt(5)*sqrt(2) -2/3]] 

    For numerical approximations of the solutions, you can instead use:

    sage: solns = solve([eq1,eq2,eq3,p==1],p,q,x,y, solution_dict=True)sage: [[s[p].n(30), s[q].n(30), s[x].n(30), s[y].n(30)] for s in solns][[1.0000000, 8.0000000, -4.8830369, -0.13962039], [1.0000000, 8.0000000, 3.5497035, -1.1937129]] 

    (The function n prints a numerical approximation, and the argument is the number of bits of

    precision.)

    http://www.sagemath.org/doc/constructions/http://www.sagemath.org/doc/constructions/http://www.sagemath.org/doc/constructions/

  • 8/17/2019 OU LV 2 Priprema

    12/25

    5.2. Solving Equations Numerically

    Often times, solve will not be able to find an exact solution to the equation or equations

    specified. When it fails, you can use find_root to find a numerical solution. For example,

    solve does not return anything interesting for the following equation:

    sage: theta = var('theta')sage: solve(cos(theta)==sin(theta), theta)

    [sin(theta) == cos(theta)] 

    On the other hand, we can use find_root to find a solution to the above equation in the

    range 0

  • 8/17/2019 OU LV 2 Priprema

    13/25

    To compute the partial fraction decomposition of  1/( x2−1):sage: f = 1/((1+x)*(x-1))sage: f.partial_fraction(x)-1/2/(x + 1) + 1/2/(x - 1) 

    5.4. Solving Differential Equations

    You can use Sage to investigate ordinary differential equations. To solve the

    equation  x′+ x−1=0:sage: t = var('t') # define a variable t sage: x = function('x',t) # define x to be a function of that variable sage: DE = diff(x, t) + x - 1 sage: desolve(DE, [x,t])

    (c + e^t)*e^(-t) 

    This uses Sage’s interface to Maxima [Max], and so its output may be a bit different from

    other Sage output. In this case, this says that the general solution to the differential

    equation is  x(t )=e−t (et +c).

    You can compute Laplace transforms also; the Laplace transform  of  t 2et −sin(t ) iscomputed as follows:

    sage: s = var("s")sage: t = var("t")sage: f = t^2*exp(t) - sin(t)

    sage: f.laplace(t,s)-1/(s^2 + 1) + 2/(s - 1)^3 

    Here is a more involved example. The displacement from equilibrium (respectively) for a

    coupled spring attached to a wall on the left

    |------\/\/\/\/\---|mass1|----\/\/\/\/\/----|mass2|spring1 spring2

    is modeled by the system of 2nd order differential equations

       

    where mi  is the mass of object i , xi  is the displacement from equilibrium of mass i ,and k i is the spring constant for spring i .

    Example: Use Sage to solve the above problem

    with m1=2, m2=1, k 1=4, k 2=2, x1(0)=3, x′1(0)=0, x2(0)=3, x′2(0)=0.

    http://www.sagemath.org/doc/tutorial/bibliography.html#maxhttp://www.sagemath.org/doc/tutorial/bibliography.html#maxhttp://www.sagemath.org/doc/tutorial/bibliography.html#maxhttp://www.sagemath.org/doc/tutorial/bibliography.html#max

  • 8/17/2019 OU LV 2 Priprema

    14/25

    Solution: Take the Laplace transform of the first equation (with the notation

     x= x1, y= x2):sage: de1 = maxima("2*diff(x(t),t, 2) + 6*x(t) - 2*y(t)")sage: lde1 = de1.laplace("t","s"); lde12*(-?%at('diff(x(t),t,1),t=0)+s^2*'laplace(x(t),t,s)-x(0)*s)-

    2*'laplace(y(t),t,s)+6*'laplace(x(t),t,s)  

    This is hard to read, but it says that

    −2 x′(0)+2 s2⋅ X ( s)−2 sx(0)−2Y ( s)+6 X ( s)=0 

    (where the Laplace transform of a lower case function like x(t )  is the upper case

    function X ( s)). Take the Laplace transform of the second equation:sage: de2 = maxima("diff(y(t),t, 2) + 2*y(t) - 2*x(t)")

    sage: lde2 = de2.laplace("t","s"); lde2-?%at('diff(y(t),t,1),t=0)+s^2*'laplace(y(t),t,s)+2*'laplace(y(t),t,s)-2*'laplace(x(t),t,s)-y(0)*s 

    This says

    −Y ′(0)+ s2Y ( s)+2Y ( s)−2 X ( s)− sy(0)=0. 

    Plug in the initial conditions for  x(0),  x′(0),  y(0), and  y′(0), and solve the resulting two

    equations:sage: var('s X Y')(s, X, Y) sage: eqns = [(2*s^2+6)*X-2*Y == 6*s, -2*X +(s^2+2)*Y == 3*s]sage: solve(eqns, X,Y)[[X == 3*(s^3 + 3*s)/(s^4 + 5*s^2 + 4), Y == 3*(s^3 + 5*s)/(s^4 + 5*s^2 + 4)]] 

    Now take inverse Laplace transforms to get the answer:

    sage: var('s t')(s, t) 

    sage: inverse_laplace((3*s^3 + 9*s)/(s^4 + 5*s^2 + 4),s,t)cos(2*t) + 2*cos(t) sage: inverse_laplace((3*s^3 + 15*s)/(s^4 + 5*s^2 + 4),s,t)

    -cos(2*t) + 4*cos(t) 

    Therefore, the solution is

     x1(t )=cos(2t )+2cos(t ), x2(t )=4cos(t )−cos(2t ). 

  • 8/17/2019 OU LV 2 Priprema

    15/25

    The individual components can be plotted using

    sage: t = var('t')sage: p1 = plot(cos(2*t) + 2*cos(t), (t,0, 2*pi), rgbcolor=hue(0.3))sage: p2 = plot(4*cos(t) - cos(2*t), (t,0, 2*pi), rgbcolor=hue(0.6))

    sage: show(p1 + p2)

    6. Symbolic Expressions

    In the first tutorial, we defined functions using notation similar to that one would use in

    (say) a calculus course.

    There is a useful variant on this - defining expressions involving variables. This will give us

    the opportunity to point out several important, and sometimes subtle, things.

    In the cell below, we define an expression  FV  which is the future value of an investment of

    $100, compounded continuously. We then substitute in values for r  and t  which calculate

    the future value for t =5 years and r =5% nominal interest.sage: var('r,t')(r, t) sage: FV=100*e^(r*t)sage: FV(r=.05,t=5)

    128.402541668774 

    The previous cells point out several things to remember when working with symbolic

    expressions. Some are fairly standard.

      An asterisk (*) signifies multiplication. This should be how you always do

    multiplication.

      Although it is possible to allow implicit multiplication, this can easily lead to

    ambiguity.

      We can access the most important constants; for instance,  e stands for the

    constant 2.71828.... Likewise, pi (or π ) and  I  (think complex numbers) are alsodefined.

      Of course, if you redefine e to be something else, all bets are off!

    However, two others may be unfamiliar, especially if you have not used much mathematical

    software before.

      You must tell Sage what the variables are before using them in a symbolic

    expression.

      We did that above by typing var('r,t').

      This is automatically done with the  f ( x) notation, but without that it is necessary, sothat Sage knows one intends t (for instance) is a symbolic variable and not a number

    or something else.

     If you then wish to substitute some values into the expression, you must explicitly

    tell Sage which variables are being assigned which values.

  • 8/17/2019 OU LV 2 Priprema

    16/25

      For instance, above we used FV(r=.05,t=5) to indicate the precise values

    of  r  and t .

    Notice that when we define a function, we don’t need to specify which variable has which

    value. In the function defined below, we have already specified an order.sage: FV2(r,t)=100*e^(r*t)sage: FV2(.05,5)

    128.402541668774 

    In this case it is clear that r  is first and t  is second.

    But with FV=100*e^(r*t), there is no particular reason r  or t  should be first.sage: FV(r=.05,t=5); FV(t=5,r=.05)128.402541668774 

    128.402541668774 

    This is why we receive a deprecation error message when we try to do   FV  withoutexplicitly mentioning the variables.

    sage: FV(5,.05)doctest:...: DeprecationWarning: Substitution using function-call syntaxand unnamed arguments is deprecated and will be removed from a futurerelease of Sage; you can use named arguments instead, like EXPR(x=...,y=...) See http://trac.sagemath.org/5930 for details. 128.402541668774 

    In this case, the outcome is the same, since rt =tr ! Of course, in most expressions, onewould not be so lucky, as the following example indicates.

    sage: y = var('y')sage: G = x*y^2 sage: G(1,2); G(2,1)4 2 

    Also remember that when we don’t use function notation, we’ll need to define our

    variables.

    One of the great things we can do with expressions is manipulate them. Let’s make a typical

    expression.

    sage: z = (x+1)^3 

  • 8/17/2019 OU LV 2 Priprema

    17/25

    In the cells below, you’ll notice something new: the character #. In Sage (and in Python ),

    anything on a single line after the number/pound sign (theoctothorp ) is ignored. We say

    that # is a comment character. We use it below to mention alternative ways to do the same

    thing.

    sage: expand(z) # or z.expand() x^3 + 3*x^2 + 3*x + 1 sage: y = expand(z)sage: y.factor() # or factor(y) 

    (x + 1)^3 

    In the previous cell, we assigned  the expression which is the expansion of   z  to the

    variable  y with the first line. After that, anything we want to do to the expansion of   z  can

    be done by doing it to  y.

    There are more commands like this as well. Notice that  z  will no longer be( x+1)3 after thiscell is evaluated, since we’ve assigned  z  to a (much more complex) expression.sage: z = ((x - 1)^(3/2) - (x + 1)*sqrt(x - 1))/sqrt((x - 1)*(x + 1))sage: z.simplify_full()

    -2*sqrt(x - 1)/sqrt(x^2 - 1) 

    http://www.python.org/http://www.python.org/http://www.python.org/http://en.wikipedia.org/wiki/Number_signhttp://en.wikipedia.org/wiki/Number_signhttp://en.wikipedia.org/wiki/Number_signhttp://www.python.org/

  • 8/17/2019 OU LV 2 Priprema

    18/25

    7. Plotting

    Sage can produce two-dimensional and three-dimensional plots.

    7.1. Basic 2D Plotting

    One of the other basic uses of mathematics software is easy plotting. Here, we include a

    brief introduction to the sorts of plotting which will prepare us to use Sage in calculus.

    (There will be a separate tutorial for more advanced plotting techniques.)

    Recall that we can generate a plot using fairly simple syntax. Here, we define a function

    of   x and plot it between −1 and 1.sage: f(x)=x^3+1 

    sage: plot(f,(x,-1,1))

    We can give the plot a name, so that if we want to do something with the plot later, we

    don’t have to type out the entire plot command. Remember, this is called  assigning  the

    plot to the name/variable.

    In the next cell, we give the plot the name  P .sage: P=plot(f,(x,-1,1))

    One plot is nice, but one might want to superimpose plots as well. For instance, the tangentline to  f  at  x=0 is just the line  y=1, and we might want to show this together with theplot.

    So let’s plot this line in a different color, and with a different style for the line, but over the

    same interval.

    sage: Q=plot(1,(x,-1,1),color="red", linestyle="--")sage: Q

    Because we put Q in a line by itself at the end, it shows. We were able to use just one cell

    to define Q and show it, by putting each command in a separate line in the same input cell.

    Now to show the plots superimposed on each other, we simply add them.

    sage: P+Q

    Suppose we wanted to view a detail of this.

      We could create another plot with different endpoints.

      Another way is to keep the currently created plots, but to set the viewing window

    using the show command, as below.

    sage: (P+Q).show(xmin=-.1,xmax=.1,ymin=.99,ymax=1.01)

  • 8/17/2019 OU LV 2 Priprema

    19/25

    Since the axes no longer cross in the frame of reference, Sage shows a short gap between

    the horizontal and vertical axes.

    There are many options one can pass in for various purposes.

      Some require quotes around the values.

      Such as the color option when we made a "red" line.

      Some do not.

      Such as the xmin in the previous plot, where the minimum x value was just −.1 

    Usually (though not always) quotes are required for option values which are words or

    strings of characters, and not required for numerical values.

    Two of the most useful of these options help in labeling graphs.

      The axes_labels option labels the axes.

      As with the word processor, we can use dollar signs (like in LaTeX) to make the labelstypeset nicely.

    Here we need both quotes and brackets for proper syntax, since there are two axes to label

    and the labels are not actually numbers.

    sage: plot(f,(x,-1,1),axes_labels=['$x$','$y$'],legend_label='$f(x)$',show_legend=True)

      The legend_label option is especially useful with multiple plots.

      LaTeX notation works here too.

    In the graphic above, we needed to explicitly ask to show the label. With multiple graphs

    this should not be necessary.

    sage: P1 = plot(f,(x,-1,1),axes_labels=['$x$','$y$'],legend_label='$f(x)$')sage: P2 = plot(sin,(x,-1,1),axes_labels=['$x$','$y$'],legend_label='$\sin(x)$',color='red')sage: P1+P2

    One additional useful note is that plots of functions with vertical asymptotes may need their

    vertical viewing range set manually; otherwise the asymptote may really go to infinity!

    sage: plot(1/x^2,(x,-10,10),ymax=10)

    Remember, you can use the command plot? to find out about most of the options

    demonstrated above.

    Below, you can experiment with several of the plotting options.

      Just evaluate the cell and play with the sliders, buttons, color picker, etc., to change

    the plot options.

      You can access low-level options like the initial number of plotted points, or high-

    level ones like whether axes are shown or not.

      This uses a feature of Sage called “interacts”, which is a very powerful way to engagestudents in exploring a problem.

  • 8/17/2019 OU LV 2 Priprema

    20/25

    sage: x = var('x')sage: @interact sage: def plot_example(f=sin(x^2),r=range_slider(-5,5,step_size=1/4,default=(-3,3)),... color=color_selector(widget='colorpicker'),... thickness=(3,(1..10)),... adaptive_recursion=(5,(0..10)),adaptive_tolerance=(0.01,(0.001,1)),... plot_points=(20,(1..100)),... linestyle=['-','--','-.',':'],... gridlines=False, fill=False,... frame=False, axes=True ... ):... show(plot(f, (x,r[0],r[1]), color=color, thickness=thickness,... adaptive_recursion=adaptive_recursion,... adaptive_tolerance=adaptive_tolerance,plot_points=plot_points,... linestyle=linestyle, fill=fill if fill else None),

    ... gridlines=gridlines, frame=frame, axes=axes)

    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”.   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  –  (default: "linear") string. The 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 Graphics is initialized.

      xmin - starting x value

      xmax - ending x value

      ymin - starting y value in the rendered figure

      ymax - ending y value in the rendered figure

      color - an RGB tuple (r,g,b) with each of r,g,b between 0 and 1, or a color name as

    a string (e.g., ‘purple’), or an HTML color such as ‘#aaff0b’. 

      detect_poles - (Default: False) If set to True poles are detected. If set to “show”

    vertical asymptotes are drawn.  legend_color - the color of the text for this item in the legend

    http://www.sagemath.org/doc/reference/plotting/sage/plot/graphics.html#sage.plot.graphics.Graphicshttp://www.sagemath.org/doc/reference/plotting/sage/plot/graphics.html#sage.plot.graphics.Graphicshttp://www.sagemath.org/doc/reference/plotting/sage/plot/graphics.html#sage.plot.graphics.Graphicshttp://www.sagemath.org/doc/reference/plotting/sage/plot/graphics.html#sage.plot.graphics.Graphics

  • 8/17/2019 OU LV 2 Priprema

    21/25

      legend_label - the label for this item in the legend

    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

    Any MATPLOTLIB line option may also be passed in. E.g.,

      linestyle - (default: “-”) The style of the line, which is one ofo  "-" or "solid" 

    o  "--" or "dashed" 

    o  "-." or "dash dot" 

    o  ":" or "dotted" 

    o  "None" or " " or "" (nothing)

    The linestyle can also be prefixed with a drawing style (e.g., "steps--")

    o  "default" (connect the points with straight lines)

    o  "steps" or "steps-pre"  (step function; horizontal line is to the left of

    point)o  "steps-mid" (step function; points are in the middle of horizontal lines)

    o  "steps-post" (step function; horizontal line is to the right of point)

      marker - The style of the markers, which is one of

    o  "None" or " " or "" (nothing) – default

    o  "," (pixel), "." (point)

    o  "_" (horizontal line), "|" (vertical line)

    o  "o" (circle), "p" (pentagon), "s" (square), "x" (x), "+" (plus), "*" (star)

    o  "D" (diamond), "d" (thin diamond)

    o  "H" (hexagon), "h" (alternative hexagon)

    o  "" (triangle right), "^" (triangle up), "v" (triangledown)

    o  "1" (tri down), "2" (tri up), "3" (tri left), "4" (tri right)

    o  0 (tick left), 1 (tick right), 2 (tick up), 3 (tick down)

    o  4 (caret left), 5 (caret right), 6 (caret up), 7 (caret down)

    o  "..." (math TeX string)

      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 alist of real numbers, or an equation in one variable.

  • 8/17/2019 OU LV 2 Priprema

    22/25

    FILLING OPTIONS:

      fill - (Default: False) One of:

    o  “axis” or True: Fill the area between the function and the x-axis.

    o  “min”: Fill the area between the function and its minimal value.

    o  “max”: Fill the area between the function and its maximal value. 

    o  a number c: Fill the area between the function and the horizontal line y = c.

    o  a function g: Fill the area between the function that is plotted and g.

    o  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 .)

      fillcolor - (default: ‘automatic’) The color of the fill. Either ‘automatic’ or a color. 

      fillalpha - (default: 0.5) How transparent the fill is. A number between 0 and 1.

    7.2. Basic 3D Plotting

    Sage can also be used to create three-dimensional plots. In both the notebook and the REPL,

    these plots will be displayed by default using the open source package [Jmol],  which

    supports interactively rotating and zooming the figure with the mouse.

    Use plot3d to graph a function of the form  f ( x, y)= z :

    sage: x, y = var('x,y')sage: plot3d(x^2 + y^2, (x,-2,2), (y,-2,2))

    Alternatively, you can use parametric_plot3d to graph a parametric surface where each

    of x,y,z is determined by a function of one or two variables (the  parameters,

    typically u and v). The previous plot can be expressed parametrically as follows:sage: u, v = var('u, v')sage: f_x(u, v) = usage: f_y(u, v) = vsage: f_z(u, v) = u^2 + v^2 

    sage: parametric_plot3d([f_x, f_y, f_z], (u, -2, 2), (v, -2, 2))

    The third way to plot a 3D surface in Sage is implicit_plot3d, which graphs a contour

    of a function like  f ( x, y, z )=0 (this defines a set of points). We graph a sphere using theclassical formula:

    sage: x, y, z = var('x, y, z')

    sage: implicit_plot3d(x^2 + y^2 + z^2 - 4, (x,-2, 2), (y,-2, 2), (z,-2, 2))

    http://www.sagemath.org/doc/tutorial/bibliography.html#jmolhttp://www.sagemath.org/doc/tutorial/bibliography.html#jmolhttp://www.sagemath.org/doc/tutorial/bibliography.html#jmolhttp://www.sagemath.org/doc/tutorial/bibliography.html#jmol

  • 8/17/2019 OU LV 2 Priprema

    23/25

    We test creating a contour_plot3:

    sage: x,y = var('x,y')sage: contour_plot(x^2-y^3+10*sin(x*y), (x, -4, 4), (y, -4,4),plot_points=121,cmap='hsv')

    or:

    sage: x,y = var('x,y')sage: f(x,y) = x^2 + y^2 sage: d = contour_plot(f, (3, 6), (3, 6))

    7.2.1. Region plot

    sage.plot.contour_plot.region_plot(f , xrange, yrange, plot_points, incol , outcol , bordercol , borderstyle, borderwidth, frame=False, axes=True, plot_points=100 , aspect_rati o=1,outcol='white' , borderwidth=None, incol='blue' , borderstyle=None, legend_label=

    None, bordercol=None, **options)

    region_plot takes a boolean function of two variables, f ( x, y) and plots the regionwhere f is True over the specified xrange and yrange as demonstrated below.region_plot(f, (xmin, xmax), (ymin, ymax), ...)

    INPUT:

      f  – a boolean function of two variables

      (xmin, xmax)  – 2-tuple, the range of x values OR 3-tuple (x,xmin,xmax) 

      (ymin, ymax)  – 2-tuple, the range of y values OR 3-tuple (y,ymin,ymax) 

      plot_points  – integer (default: 100); number of points to plot in each direction of

    the grid

      incol  – a color (default: 'blue'), the color inside the region

      outcol  – a color (default: 'white'), the color of the outside of the region

    If any of these options are specified, the border will be shown as indicated,

    otherwise it is only implicit (with color incol) as the border of the inside of the

    region.

    o  bordercol  –  a color (default: None), the color of the border('black' if borderwidth or borderstyle is specified but

    not bordercol)

    o  borderstyle  –  string (default: ‘solid’), one

    of 'solid', 'dashed', 'dotted', 'dashdot', respectively '-', '--

    ', ':', '-.'.

    o  borderwidth  – integer (default: None), the width of the border in pixels

    o  legend_label  – the label for this item in the legend

    o  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 thehorizontal axis and basey sets the base along the vertical axis.

  • 8/17/2019 OU LV 2 Priprema

    24/25

    o  scale  –  (default: "linear") string. The 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 Graphics is initialized.

    EXAMPLES:

    Here we plot a simple function of two variables:

    sage: x,y = var('x,y')sage: region_plot(cos(x^2+y^2)

  • 8/17/2019 OU LV 2 Priprema

    25/25

    If we want to keep only the region where x is positive:

    sage: region_plot([x*(x-1)*(x+1)+y^2-1], (x, -3, 2), (y, -3, 3),

    incol='lightblue', plot_points=50)

    Here we have a cut circle:

    sage: region_plot([x^2+y^2-1], (x, -2, 2), (y, -2, 2),

    incol='lightblue', bordercol='gray', plot_points=200)

    The first variable range corresponds to the horizontal axis and the second variable range

    corresponds to the vertical axis:

    sage: s,t=var('s,t')sage: region_plot(s>0,(t,-2,2),(s,-2,2))sage: region_plot(s>0,(s,-2,2),(t,-2,2))

    An example of a region plot in ‘loglog’ scale: sage: region_plot(x^2+y^2