Introduction to scripting

Many numerical problems that can be solved with a pocket calculator can be solved more easily with a script. A script is a short piece of computer code that is used to perform a calculation. In a script, variables can be defined and mathematical operations can be performed on these variables. Scripts can be written in many programming languages such as python, Matlab, or Mathematica. Below is some code that calculates the length of a vector. Try changing the values of the components of the vector and press 'execute'. The results of the calculation should appear in the 'Script Output' box. The buttons at the top add some common constants to the script.

Script Output

This scripting application uses JavaScript but you don't need to know much about programming to use a script. We will use assignment statements where a value is assigned to a variable such as x=5, the operations addition (+), subtraction (-), multiplication (*), and division (/), as well as functions such as sqrt(x) or sin(x) that are normally found on a pocket calculator. A list of these functions is displayed when the button is pressed. The results of a calculation can be written to the Script Output box using the print(x) function. Text should be put in quotes, e.g. print("Print some text"). The value of variable x can be printed with print(x) and text can be mixed with variables by concatenating them together with a + sign, print("The length is "+x+" m."). Everything after a double slash "//" is a comment and is ignored by the interpreter. Comments make the code easier to understand.

The code is interpreted line-by-line because this makes it easier to debug. This might be confusing if you are familiar with programming structures such as function definitions, conditional statements, or loops which often extend over several lines. Any programming structure that extends over several lines will not be interpreted properly but this should not be a problem because we won't be using advanced structures. The application remembers all of the variables that have been defined since the session was started so if you want to start a new problem, it is a good idea to close the tab and start and new session.