REPORTER 22.1

Example 2: Magnitude from the Three Vector Components

Example 2: Magnitude from the three vector components

Problem

Given three variables X, Y and Z calculate the vector magnitude and store it in a variable LENGTH.

Solution

JavaScript
// Get variable values from template
var x = Template.GetCurrent().GetVariableValue("X");
var y = Template.GetCurrent().GetVariableValue("Y");
var z = Template.GetCurrent().GetVariableValue("Z");

// Check that the variables exist
if (x == null) throw Error("no X variable");
if (y == null) throw Error("no Y variable");
if (z == null) throw Error("no Z variable");

// Extract numbers from variables
var X = parseFloat(x);
var Y = parseFloat(y);
var Z = parseFloat(z);

// Check that the variables are valid numbers
if (isNaN(X)) throw Error("X " + x + " is not a valid number");
if (isNaN(Y)) throw Error("Y " + y + " is not a valid number");
if (isNaN(Z)) throw Error("Z " + z + " is not a valid number");

// Calculate magnitude
var length = Math.sqrt(X*X + Y*Y + Z*Z);

// Check for valid magnitude
if (isNaN(length)) throw Error("Bad vector magnitude");

// Create new variable LENGTH
var lvar = new Variable(Template.GetCurrent(), "LENGTH",
"vector magnitude", length);

Discussion

This is done using very similar methods to example 1. The only differences here are using the function Math.sqrt() and we do not use the standard Number.toFixed() function as the length could be smaller than 2 decimal places. Instead we could use Number.toPrecision() or Number.toExponential() if we wanted to format the result instead of leaving it with several decimal places.

The source code for this example is available here .