Book Image

Sage Beginner's Guide

By : Craig Finch
1 (1)
Book Image

Sage Beginner's Guide

1 (1)
By: Craig Finch

Overview of this book

Table of Contents (17 chapters)
Sage Beginner's Guide
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Time for action – defining and using your own functions


Let's return to the series RC circuit that we have been using as an example. We will now define a function that computes the voltage across the capacitor. You can enter the following code in an input cell in a worksheet, or on the command line. When you type the colon at the end of the first line and press Enter, the cursor will automatically indent the lines that follow. Make sure that you consistently indent each line inside the function.

def RC_voltage(v0, R, C, t):
    """
    Calculate the voltage at time t for an R-C circuit
    with initial voltage v0.
    """
    tau = R * C
    return v0 * exp(-t / tau)
    
R = 250e3   # Ohms
C = 4e-6    # Farads
v0 = 100.0    # Volts
t = 1.0      # seconds

v = RC_voltage(v0, R, C, t)
print('Voltage at t=' + str(n(t, digits=4)) + 's is ' + 
    str(n(v, digits=4)) + 'V')

This block of code produces the following output:

Voltage at t=1.000s is 36.79V

If you are using the interactive shell,...