Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 4665

Defining a function in SageMath is quite easy. Give the function a name, list the arguments in parentheses, then type out the function.

Defining a function

  • Function name must start with a letter and can contain numbers and underscores (no spaces)

  • List the arguments of the function. These do not need to be defined as variables

    • For example y(t)=y_0+v_0*t+1/2*a*t^2

  • Functions can be evaluated by entering values for each argument

    • For example: y(1) yields the value of y when t=1.

x(x_0,v_0x,t)=x_0+v_0x*t #Position equation x(0,2,8) #Evaluate the position when x_0=0, v_0x=2, and t=8 x(10,-1,4) #Evaluate the position when x_0=10, v_0x=-1, and t=4
16 6

Taking Derivatives

  • Can either use diff(f(x),x) or f(x).diff(x)

  • diff() or derivative() are identical

  • Specify variable to differentiate with respect to

  • Indicate the order of the derivative

y_0,v_0y,a_y=var('y_0,v_0y,a_y') #Define all variables y(t)=y_0+v_0y*t+1/2*a_y*t^2 #Define y(t) ### A couple of different ways to take the derivative of y with respect to t y(t).diff(t) diff(y(t),t) derivative(y(t),t) ### Second derivative of y with respect to t should return the acceleration y(t).diff(t,2) diff(y(t),t,2)
a_y*t + v_0y a_y*t + v_0y a_y*t + v_0y a_y a_y

The SageMath derivative returns a function so you can assign it a name or evaluate it at a point just like with other functions.

diff(y(t),t)(t=1) v(t)=diff(y(t),t) v(1)
a_y + v_0y a_y + v_0y

Plotting Functions

  • Use the plot() command to create a plot

    • Arguments of plot() include the function to plot, the variable to plot against, and the variable range

      • plot(y(t),t,0,10) plots the function y(t) vs. t from t=0 to t=10

  • Plots can be given variable names which is useful for modifying features of the plot

    • For example: P1=plot(y(t),t,0,10)

  • The show() command displays the plot on the screen

    • For example: P1.show()

y_plot(t)=y(t).substitute(a_y=-9.8,v_0y=20,y_0=10) #Must substitute numerical values for all variables (except t) in order to plot pos_plot=plot(y_plot(t),t,0,10,title='Position vs. Time') pos_plot.show() #Display pos_plot on the screen

Try It Yourself

  • Plot the function F=Gm1m2r2F=G \frac{m_1 m_2}{r^2} vs. rr

    • Use .substitute() to input values for G, m1m_1, and m2m_2

    • Choose a minimum value of rr so graph does not blow up near the origin

#Input your work here

Plotting Multiple Functions

  • Plots can be 'added' together for display on the same graph