5.4 Making Our Own Module
113
package is that the results cannot automatically be imported into your code and
used for further analysis. On the other hand, WolframAlpha has the advantage that
it displays many additional mathematical results related to the given problem. For
example, if we type 2x + 3x - y in WolframAlpha, it not only simplifies the
expression to 5x - y, but it also makes plots of the function f (x, y) = 5x − y,
solves the equation 5x − y = 0, and calculates the integral
(5x + y)dxdy. The
commercial Pro version also offers a step-by-step demonstration of the analytical
computations that solve the problem. You are encouraged to try out these commands
in WolframAlpha:
• diff(x^2, x) or diff(x**2, x)
• integrate(cos(x), x)
• simplify((x**2 + x**3)/x**2)
• limit(sin(x)/x, x, 0)
• solve(5*x - 15, x)
WolframAlpha is very flexible with respect to syntax. In fact, WolframAlpha will
use your input to guess what you want it to do! Depending on what you write, it
may be more or less easy to do that guess, of course. However, in WolframAlpha’s
response, you are also told how your input was interpreted, so that you may adjust
your input in a second try.
Another impressive tool for symbolic computations is Sage, 6 which is a very
comprehensive package with the aim of “creating a viable free open source
alternative to Magma, Maple, Mathematica and Matlab”. Sage is implemented in
Python. Projects with extensive symbolic computations will certainly benefit from
exploring Sage.
5.4 Making Our Own Module
As we know by now, Python has a huge collection of useful modules and packages
written by clever people. This far, we have experienced how these libraries (math,
numpy, matplotlib, etc.) could simplify our own programming, making ready and
professional code available through simple import statements. This is very good, but
it gets even better, since it is straight forward (whether we are programming newbies
or not) to also create modules containing our own code.
What is a module then, really? The truth is, that we may regard any of the
Python scripts we have presented in this book as a module! In fact, any text file
with extension .py that contains Python code written with a text editor, is a module.
If the file name is my_module.py, then the module name is my_module. Up until
now, we have written .py files for execution as programs. To design and use such
files as module files, however, there are a few things we better get conscious about.
To bring across the essential points, we will develop our own little demonstration
module for vertical motion, named vertical_motion (surprising!). The motion
is of the kind we have addressed also previously in this book, i.e., a special case
of projectile motion, in which an object starts out with some vertical velocity, and
6 http://sagemath.org/.
Précédent

- 134/350

Suivant